【优先队列】LeetCode 973. 最接近原点的 K 个点
题目链接
思路
使用优先队列处理前k大问题
代码
class Solution {
class Node{
int x;
int y;
double distance;
}
public int[][] kClosest(int[][] points, int k) {
int[][] result = new int[k][2];
PriorityQueue<Node> queue = new PriorityQueue<>(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return Double.compare(o2.distance, o1.distance);
}
});
for(int i = 0; i < points.length; i++){
Node node = new Node();
node.x = points[i][0];
node.y = points[i][1];
node.distance = Math.sqrt(Math.pow(node.x, 2) + Math.pow(node.y, 2));
queue.add(node);
if(queue.size() > k){
queue.poll();
}
}
for(int i = 0; i < k; i++){
Node node = queue.poll();
result[i][0] = node.x;
result[i][1] = node.y;
}
return result;
}
}