Skip to content

Commit 0e9cca5

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

File tree

1 file changed

+13
-11
lines changed

1 file changed

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

7-
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
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]));
810

9-
for (int i = 0; i < points.length; i++) {
10-
int distance = (Math.abs(points[i][0]) * Math.abs(points[i][0]))
11-
+ (Math.abs(points[i][1]) * Math.abs(points[i][1]));
12-
pq.offer(new int[] { i, distance });
11+
for (int[] pair : points) {
12+
pq.offer(pair);
13+
14+
if (pq.size() > K) {
15+
pq.poll();
16+
}
1317
}
1418

15-
ArrayList<int[]> result = new ArrayList<>();
16-
while (K > 0) {
17-
result.add(points[pq.poll()[0]]);
18-
--K;
19+
while (K-- > 0) {
20+
result.add(pq.poll());
1921
}
2022

21-
return result.toArray(new int[result.size()][]);
23+
return result.toArray(new int[0][]);
2224
}
2325
}

0 commit comments

Comments
 (0)