-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathfind-k-closest-elements.py
More file actions
55 lines (41 loc) · 1.43 KB
/
find-k-closest-elements.py
File metadata and controls
55 lines (41 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import heapq
import random
from collections import deque
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
def bisect(arr, x):
left, right = 0, len(arr) - 1
result = 0
while left < right:
middle = (left + right) // 2
if arr[middle] < x:
left = middle + 1
result = left
elif arr[middle] > x:
right = middle - 1
result = right
else:
return middle
return result
center = bisect(arr, x)
left, right = max(center - k, 0), min(center + k, len(arr) - 1)
while right - left >= k:
if abs(arr[left] - x) > abs(arr[right] - x):
left += 1
else:
right -= 1
return arr[left:right + 1]
def findClosestElementsHeap(self, arr: List[int], k: int, x: int) -> List[int]:
def construct_heap(heap, arr, x):
for num in arr:
heapq.heappush(heap, (abs(x - num), num))
heap = []
queue = deque()
construct_heap(heap, arr, x)
for _ in range(k):
_, val = heapq.heappop(heap)
if not queue or val <= queue[0]:
queue.appendleft(val)
else:
queue.append(val)
return list(queue)