-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathk_closest_element.py
More file actions
36 lines (26 loc) · 867 Bytes
/
k_closest_element.py
File metadata and controls
36 lines (26 loc) · 867 Bytes
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
import heapq
class Solution:
def findClosestElements(self, arr, k, x):
if not arr:
return []
def calculate_difference(num):
return abs(num - x)
heap = [] # max-heap (-difference, num)
for num in arr:
difference = -calculate_difference(num)
if len(heap) < k:
heapq.heappush(heap, (difference, num))
elif difference > heap[0][0]:
heapq.heappushpop(heap, (difference, num))
return sorted([num for _, num in heap])
# Time Complexity: O(n log k)
# Space Complexity: O(k)
if __name__ == "__main__":
solution = Solution()
arr = [1, 2, 3, 4, 5]
k = 4
x = 3
result = solution.findClosestElements(arr, k, x)
assert result == [1, 2, 3, 4]
print(result)
print("Test Cased 1 Passed!")