Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Example 1:
Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]]
class Solution {
public int[][] kClosest(int[][] points, int k) {
int[][] res = new int[k][2];
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a,b) -> (a[0] * a[0]+ a[1] * a[1]) - (b[0] * b[0] + b[1] * b[1])); //比較該點與原點距離
for(int[] point: points){
minHeap.add(point);
}
for(int i=0; i < k; i++){
res[i] = minHeap.poll();
}
return res;
}
}
Time: O(n * log(n)),其中 n 是點的總數 Space: O(n + k),其中 n 是點的總數,k 是要返回的最接近點的數量