973. K Closest Points to Origin
We have a list of points
on the plane. Find the K
closest points to the origin (0, 0)
.
(Here, the distance between two points on a plane is the Euclidean distance.)
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]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)
1 class Solution { 2 // Approach 1 3 public int[][] kClosest1(int[][] points, int K) { 4 PriorityQueue<int[]> pq = new PriorityQueue<int[]>((p1, p2) -> p2[0] * p2[0] + p2[1] * p2[1] - p1[0] * p1[0] - p1[1] * p1[1]); 5 for (int[] p : points) { 6 pq.offer(p); 7 if (pq.size() > K) { 8 pq.poll(); 9 } 10 } 11 int[][] res = new int[K][2]; 12 while (K > 0) { 13 res[--K] = pq.poll(); 14 } 15 return res; 16 } 17 18 // Approach 2 19 public int[][] kClosest2(int[][] points, int K) { 20 int len = points.length, l = 0, r = len - 1; 21 while (l <= r) { 22 int mid = partition(points, l, r); 23 if (mid == K) { 24 break; 25 } else if (mid < K) { 26 l = mid + 1; 27 } else { 28 r = mid - 1; 29 } 30 } 31 return Arrays.copyOfRange(points, 0, K); 32 } 33 34 private int compare(int[] p1, int[] p2) { 35 return p1[0] * p1[0] + p1[1] * p1[1] - p2[0] * p2[0] - p2[1] * p2[1]; 36 } 37 38 private int partition(int[][] A, int start, int end) { 39 int p = start; 40 for (int i = start; i <= end - 1; i++) { 41 if (compare(A[i], A[end]) < 0) { 42 swap(A, p, i); 43 p++; 44 } 45 } 46 swap(A, p, end); 47 return p; 48 } 49 50 private void swap(int[][] nums, int i, int j) { 51 int[] temp = nums[i]; 52 nums[i] = nums[j]; 53 nums[j] = temp; 54 } 55 }