class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = []
for i, point in enumerate(points):
dis = self._distance(point, (0, 0))
# heappush: inserting an item to a heap of size k take O(logK) time
heapq.heappush(heap, (-dis, i)) # 这里也可以换成(-dis, x, y)入堆
if len(heap) > k:
heapq.heappop(heap)
res = []
for dis, i in heap:
res.append(points[i])
return res
def _distance(self, point1, point2):
x1, y1 = point1
x2, y2 = point2
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5