精華區beta Marginalman 關於我們 聯絡資訊
※ 引述《Rushia (みけねこ的鼻屎)》之銘言: : 658. Find K Closest Elements : 說明: : 給定一個排序好的陣列arr、一個數字k和一個數字x,我們需返回一個大小為k的列表, : 其中的數字要是最接近x的數字,若數字一樣接近則數字小的優先,返回的列表必須也是 : 排序好的。 : Example 1: : Input: arr = [1,2,3,4,5], k = 4, x = 3 : Output: [1,2,3,4] 思路: 1.看到題目給 sorted array 直覺就是 binary search 可以O(log(n))搜到 x 能插入的位置 也就是 a[i] <= x <= a[i+1] python 的 bisect.left 可以插到 a[i] < x <= a[i+1] 2.之後就比較 a[i] 和 a[i+1] 哪個離 x 比較近 然後後面就老招了 維護左界右界 左邊離 x 比較近就往左推 反之往右推 3.不停比較直到右界-左界>k Python code: class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: n = len(arr) right = bisect_left(arr, x) left = right - 1 while right-left <= k: if right >= n: left -= 1 elif left < 0: right += 1 elif arr[right]-x >= x-arr[left]: left -= 1 else: right += 1 return arr[left+1:right] 時間複雜度O(log(n)+k) -- 蛤? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.233.144 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1664419555.A.7AD.html
Ericz7000: 大師 09/29 10:46
Rushia: 大師 09/29 10:48
soulgem: 那麼如果停在框出來的區域比 k 小再往外看會有風險嗎? 09/29 10:56
不太懂你意思 框出來的區域比 k 小會繼續框
wwndbk: 大師 09/29 10:57
Rushia: 他有邊界檢查阿第一行和第二行 09/29 10:57
對 上面沒講到 撞到邊邊就直接往另一邊框 ※ 編輯: pandix (111.251.233.144 臺灣), 09/29/2022 11:11:25
JerryChungYC: 大師 09/29 12:24