|
3 | 3 | import java.util.Comparator;
|
4 | 4 | import java.util.PriorityQueue;
|
5 | 5 |
|
| 6 | +/** |
| 7 | + * 973. K Closest Points to Origin |
| 8 | + * |
| 9 | + * We have a list of points on the plane. Find the K closest points to the origin (0, 0). |
| 10 | + * |
| 11 | + * (Here, the distance between two points on a plane is the Euclidean distance.) |
| 12 | + * |
| 13 | + * You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) |
| 14 | + * |
| 15 | + * |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * |
| 19 | + * Input: points = [[1,3],[-2,2]], K = 1 |
| 20 | + * Output: [[-2,2]] |
| 21 | + * Explanation: |
| 22 | + * The distance between (1, 3) and the origin is sqrt(10). |
| 23 | + * The distance between (-2, 2) and the origin is sqrt(8). |
| 24 | + * Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. |
| 25 | + * We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. |
| 26 | + * Example 2: |
| 27 | + * |
| 28 | + * Input: points = [[3,3],[5,-1],[-2,4]], K = 2 |
| 29 | + * Output: [[3,3],[-2,4]] |
| 30 | + * (The answer [[-2,4],[3,3]] would also be accepted.) |
| 31 | + * |
| 32 | + * |
| 33 | + * Note: |
| 34 | + * |
| 35 | + * 1 <= K <= points.length <= 10000 |
| 36 | + * -10000 < points[i][0] < 10000 |
| 37 | + * -10000 < points[i][1] < 10000 |
| 38 | + * */ |
6 | 39 | public class _973 {
|
7 | 40 |
|
8 | 41 | public static class Solution1 {
|
9 | 42 | public int[][] kClosest(int[][] points, int K) {
|
10 | 43 | int[][] ans = new int[K][2];
|
11 | 44 |
|
12 |
| - PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() { |
13 |
| - @Override |
14 |
| - public int compare(int[] o1, int[] o2) { |
15 |
| - double dist1 = getDistance(o1); |
16 |
| - double dist2 = getDistance(o2); |
17 |
| - |
18 |
| - if (dist1 > dist2) { |
19 |
| - return 1; |
20 |
| - } else if (dist1 < dist2) { |
21 |
| - return -1; |
22 |
| - } else { |
23 |
| - return 0; |
24 |
| - } |
| 45 | + PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> { |
| 46 | + double dist1 = getDistance(o1); |
| 47 | + double dist2 = getDistance(o2); |
| 48 | + |
| 49 | + if (dist1 > dist2) { |
| 50 | + return 1; |
| 51 | + } else if (dist1 < dist2) { |
| 52 | + return -1; |
| 53 | + } else { |
| 54 | + return 0; |
25 | 55 | }
|
26 | 56 | });
|
27 | 57 |
|
28 | 58 | for (int[] point : points) {
|
29 | 59 | pq.add(point);
|
30 | 60 | }
|
31 | 61 |
|
32 |
| - for (int i=0; i<K; i++) { |
| 62 | + for (int i = 0; i < K; i++) { |
33 | 63 | ans[i] = pq.poll();
|
34 | 64 | }
|
35 | 65 |
|
|
0 commit comments