|
1 | 1 | class Solution {
|
2 | 2 | public int[][] kClosest(int[][] points, int K) {
|
3 | 3 | if (points == null || points.length == 0) {
|
4 |
| - return new int[][] {}; |
| 4 | + return new int[0][0]; |
5 | 5 | }
|
6 | 6 |
|
7 |
| - List<int[]> result = new ArrayList<>(); |
8 |
| - PriorityQueue<int[]> pq = new PriorityQueue<>( |
9 |
| - (p1, p2) -> (p2[0] * p2[0] + p2[1] * p2[1]) - (p1[0] * p1[0] + p1[1] * p1[1])); |
| 7 | + int low = 0, high = points.length - 1; |
10 | 8 |
|
11 |
| - for (int[] pair : points) { |
12 |
| - pq.offer(pair); |
| 9 | + while (low < high) { |
| 10 | + int idx = quickSelect(points, low, high); |
13 | 11 |
|
14 |
| - if (pq.size() > K) { |
15 |
| - pq.poll(); |
| 12 | + if (idx == K) { |
| 13 | + break; |
| 14 | + } else if (idx < K) { |
| 15 | + low = idx + 1; |
| 16 | + } else { |
| 17 | + high = idx - 1; |
16 | 18 | }
|
17 | 19 | }
|
18 | 20 |
|
19 |
| - while (K-- > 0) { |
20 |
| - result.add(pq.poll()); |
| 21 | + return Arrays.copyOf(points, K); |
| 22 | + } |
| 23 | + |
| 24 | + private int quickSelect(int[][] points, int low, int high) { |
| 25 | + int idx = low, pivot = high; |
| 26 | + int pivotDistance = distance(points[pivot]); |
| 27 | + |
| 28 | + for (int i = low; i < high; i++) { |
| 29 | + if (distance(points[i]) < pivotDistance) { |
| 30 | + swap(points, i, idx); |
| 31 | + ++idx; |
| 32 | + } |
21 | 33 | }
|
22 | 34 |
|
23 |
| - return result.toArray(new int[0][]); |
| 35 | + swap(points, idx, pivot); |
| 36 | + return idx; |
| 37 | + } |
| 38 | + |
| 39 | + private void swap(int[][] points, int low, int high) { |
| 40 | + int[] temp = points[low]; |
| 41 | + points[low] = points[high]; |
| 42 | + points[high] = temp; |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + private int distance(int[] pair) { |
| 47 | + return pair[0] * pair[0] + pair[1] * pair[1]; |
24 | 48 | }
|
25 | 49 | }
|
0 commit comments