LeetCode 973
最简单的方法是都求出来,然后sort一下,取k个小的就好了。
实际上我们是不需要完全排序的,那么可以考虑heap,只保留k个小的,然后把其他的都pop掉。那么可以用一个max堆。超过k之后把最大的pop掉。
#python中的缺省的是min堆,转为负数当作max堆用。
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
minh = []
for x,y in points:
collections._heapq.heappush(minh, [-(x*x + y*y), x, y])
if len(minh) > K:
collections._heapq.heappop(minh)
result = []
for _, x, y in minh:
result.append([x,y])
return result