973. 最接近原点的 K 个点
我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。
(这里,平面上两点之间的距离是欧几里德距离。)
你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。
思路:暴力排序,时间复杂度O(nlogn),空间复杂度O(logn)
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
distance,ans = [],[]
for i in range(len(points)):
x,y = points[i]
distance.append([x**2+y**2,i])
distance.sort(key=lambda x:x[0])
for j in range(K):
ans.append(points[distance[j][1]])
return ans
优化思路,优先队列
(heapq堆数据结构最重要的特征是heap[0]永远是最小的元素)
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
q = [(-x ** 2 - y ** 2, i) for i, (x, y) in enumerate(points[:])]
heapq.heapify(q)
for i in range(K,len(points)):
x,y = points[i]
dist = -x ** 2 - y ** 2
if dist > q[0][0]:
heapq.heappushpop(q,(dist,i))
return [points[identity] for (_,identity) in q]