|
| 1 | +## 973. K Closest Points to Origin |
| 2 | + |
| 3 | +### Question |
| 4 | +We have a list of points on the plane. Find the K closest points to the origin (0, 0). |
| 5 | + |
| 6 | +(Here, the distance between two points on a plane is the Euclidean distance.) |
| 7 | + |
| 8 | +You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) |
| 9 | + |
| 10 | +``` |
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: points = [[1,3],[-2,2]], K = 1 |
| 14 | +Output: [[-2,2]] |
| 15 | +Explanation: |
| 16 | +The distance between (1, 3) and the origin is sqrt(10). |
| 17 | +The distance between (-2, 2) and the origin is sqrt(8). |
| 18 | +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. |
| 19 | +We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. |
| 20 | +Example 2: |
| 21 | +
|
| 22 | +Input: points = [[3,3],[5,-1],[-2,4]], K = 2 |
| 23 | +Output: [[3,3],[-2,4]] |
| 24 | +(The answer [[-2,4],[3,3]] would also be accepted.) |
| 25 | +``` |
| 26 | + |
| 27 | +Note: |
| 28 | +1. 1 <= K <= points.length <= 10000 |
| 29 | +2. -10000 < points[i][0] < 10000 |
| 30 | +3. -10000 < points[i][1] < 10000 |
| 31 | + |
| 32 | +### Solutions: |
| 33 | +* Method 1: PriorityQueue |
| 34 | + ```Java |
| 35 | + class Solution { |
| 36 | + public int[][] kClosest(int[][] points, int K) { |
| 37 | + PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){ |
| 38 | + @Override |
| 39 | + public int compare(int[] a, int[] b){ |
| 40 | + return a[0] * a[0] + a[1] * a[1] - b[0] * b[0] - b[1] * b[1]; |
| 41 | + } |
| 42 | + }); |
| 43 | + for(int[] point : points) pq.offer(point); |
| 44 | + int[][] res = new int[K][2]; |
| 45 | + int count = 0; |
| 46 | + for(int i = 0; i < K; i++){ |
| 47 | + res[i] = pq.poll(); |
| 48 | + } |
| 49 | + return res; |
| 50 | + } |
| 51 | + } |
| 52 | + ``` |
0 commit comments