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[][] kClosest2(int[][] points, int K) {
 4         Queue<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             K--;
14             res[K] = pq.poll();
15         }
16         return res;
17     }
18 
19     // Approach 2
20     public int[][] kClosest(int[][] points, int K) {
21         int len = points.length, l = 0, r = len - 1;
22         while (l <= r) {
23             int mid = partition(points, l, r);
24             if (mid == K) {
25                 break;
26             } else if (mid < K) {
27                 l = mid + 1;
28             } else {
29                 r = mid - 1;
30             }
31         }
32         return Arrays.copyOfRange(points, 0, K);
33     }
34 
35     private int compare(int[] p1, int[] p2) {
36         return p1[0] * p1[0] + p1[1] * p1[1] - p2[0] * p2[0] - p2[1] * p2[1];
37     }
38 
39     private int partition(int[][] A, int start, int end) {
40         int p = start;
41         for (int i = start; i <= end - 1; i++) {
42             if (compare(A[i], A[end]) < 0) {
43                 swap(A, p, i);
44                 p++;
45             }
46         }
47         swap(A, p, end);
48         return p;
49     }
50 
51     private void swap(int[][] nums, int i, int j) {
52         int[] temp = nums[i];
53         nums[i] = nums[j];
54         nums[j] = temp;
55     }
56 }

 

posted @ 2019-07-15 02:03  北叶青藤  阅读(359)  评论(0)    收藏  举报