K Closest Points to Origin
给一个数组, 里面全是点, 求到原点最近的k个点.
class Solution {
class Pair{
public int index;
public int n;
Pair(int index, int n) {
this.index = index;
this.n = n;
}
}
public int[][] kClosest(int[][] points, int K) {
PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> (a.n - b.n));
for(int i = 0; i < points.length; i++) {
pq.add(new Pair(i, dis(points[i])));
}
int[][] res = new int[K][2];
for(int i = 0; i < K; i++) {
res[i] = points[pq.poll().index];
}
return res;
}
private int dis(int[] a) {
return a[0]*a[0] + a[1]*a[1];
}
}