Find K Closest Elements LeetCode solution in Python

1
class Solution:
2
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
3

4
def sorted_distance(value, static_input=x):
5
return abs(value - static_input)
6

7
distances = []
8
result = []
9
heapq.heapify(distances)
10

11
for l, v in enumerate(arr):
12
distances.append((l, sorted_distance(value=v)))
13

14
for i in heapq.nsmallest(k, distances, key=lambda x: x[1]):
15
result.append(arr[i[0]])
16

17
result.sort()
18
return result

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0