Skip to content

Commit e679abf

Browse files
committedNov 3, 2023
feat: add solution for k closest points to origin in python
1 parent 48a9bbb commit e679abf

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
 
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
import heapq
3+
4+
def kClosest(points: List[List[int]], k: int) -> List[List[int]]:
5+
res = []
6+
priority_queue = []
7+
8+
for point in points:
9+
eucadient_distance = point[0] * point[0] + point[1] * point[1]
10+
heapq.heappush(priority_queue, (eucadient_distance, point))
11+
12+
while k > 0:
13+
priority, data = heapq.heappop(priority_queue)
14+
k -=1
15+
res.append(data)
16+
17+
return res
18+
19+
assert kClosest([[1,3],[-2,2]], 1) == [[-2,2]]

0 commit comments

Comments
 (0)
Please sign in to comment.