Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間1年前 (2024/08/14 09:52), 1年前編輯推噓4(401)
留言5則, 4人參與, 1年前最新討論串708/1548 (看更多)
https://leetcode.com/problems/find-k-th-smallest-pair-distance/description 719. Find K-th Smallest Pair Distance 給你一個陣列 nums 和一個數字k 求出差的絕對值第k小的 pair 差是多少。 思路: 1.因為測資小又沒負數所以把所有pair絕對值算出來之後 counting 找出第k小就好。 java code -------------------------------------------- class Solution { public int smallestDistancePair(int[] nums, int k) { int[] cnt = new int[1000001]; int n = nums.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { cnt[Math.abs(nums[i] - nums[j])]++; } } int l = 0; while (true) { if (cnt[l++] == 0) { continue; } k -= cnt[l - 1]; if (k <= 0) { return l - 1; } } } } -------------------------------------------- 只有10% 感覺要 binary search 或 greedy 之類 = = -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.12.105.92 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1723600341.A.9FA.html

08/14 09:55, 1年前 , 1F
全算了 TLE了 :(
08/14 09:55, 1F

08/14 09:56, 1年前 , 2F
技術大神
08/14 09:56, 2F

08/14 09:58, 1年前 , 3F
能暴力解喔 下午試試
08/14 09:58, 3F

08/14 09:59, 1年前 , 4F
我知道用binary search 但我還沒想到怎麼搜== 晚上
08/14 09:59, 4F

08/14 09:59, 1年前 , 5F
回家想
08/14 09:59, 5F
※ 編輯: Rushia (39.12.105.92 臺灣), 08/14/2024 12:09:18
文章代碼(AID): #1cl0tLdw (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cl0tLdw (Marginalman)