K Closest Points to Origin
给一个数组, 里面全是点, 求到原点最近的k个点.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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]; } } |