题目来源:力扣
题目描述:
我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。
(这里,平面上两点之间的距离是欧几里德距离。)
你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。
审题:
该题属于典型的TopK问题,我们在之前已经讨论过基于优先队列的算法,求一堆元素中的TopK元素.在那篇文章中,我们手动使用堆结构实现了优先队列.而在该文中,我们将直接使用java标准库中的PriorityQueue
数据结构.PriorityQueue
数据结构中,最小的元素优先级最高.因此,为了实现保存距离原点最近的K个点,我们需要设计优先队列,距离原点最远的点其优先级最高.因此对两点进行比较,距离原点越远,其优先级最高,该值最小.
java算法:
class Solution {
private class DistCmp implements Comparator<Integer[]>{
public int compare(Integer[]a, Integer[]b){
return Double.compare(Math.pow(b[0], 2) + Math.pow(b[1], 2),
Math.pow(a[0], 2) + Math.pow(a[1], 2));
}
}
public int[][] kClosest(int[][] points, int K) {
DistCmp cmp = new DistCmp();
PriorityQueue<Integer[]> pq = new PriorityQueue<>(10, cmp);
for(int i = 0; i < points.length; i++){
Integer[] point = new Integer[]{points[i][0], points[i][1]};
if(i < K)
pq.offer(point);
//如果当前point大于队列中的第一个,则其优先级小于队列中的最高优先级
else if(cmp.compare(point, pq.peek()) > 0){
pq.offer(point);
pq.poll();
}
}
int[][] nearK = new int[K][2];
for(int i = 0; i < K; i++){
Integer[] point = pq.poll();
nearK[i][0] = point[0];
nearK[i][1] = point[1];
}
return nearK;
}
}