题目链接
思路
使用优先队列处理前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;
}
}
标签:node,Node,973,个点,int,queue,result,new,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17034287.html