1、前言

2、思路
就是一般的求最大k个数和最小k个数的思路
3、代码
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((o1, o2) -> distance(o2) - distance(o1));
for(int i = 0; i < k; i++){
maxHeap.offer(points[i]);
}
for(int i = k; i < points.length; i++){
if(distance(points[i]) < distance(maxHeap.peek())){
maxHeap.poll();
maxHeap.offer(points[i]);
}
}
int[][] res = new int[k][2];
for(int i = 0; i < k; i++){
res[i] = maxHeap.poll();
}
return res;
}
private int distance(int[] a){
return (int)(Math.pow(a[0], 2) + Math.pow(a[1], 2));
}
}
网友评论