Skip to content

Commit b8b0d0c

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 973_K_Closest_Points_to_Origin.java
1 parent 0e9cca5 commit b8b0d0c

File tree

1 file changed

+35
-11
lines changed

1 file changed

+35
-11
lines changed
Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,49 @@
11
class Solution {
22
public int[][] kClosest(int[][] points, int K) {
33
if (points == null || points.length == 0) {
4-
return new int[][] {};
4+
return new int[0][0];
55
}
66

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;
108

11-
for (int[] pair : points) {
12-
pq.offer(pair);
9+
while (low < high) {
10+
int idx = quickSelect(points, low, high);
1311

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;
1618
}
1719
}
1820

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+
}
2133
}
2234

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];
2448
}
2549
}

0 commit comments

Comments
 (0)