K Closest Points to Origin LeetCode solution in Java

1
class Solution {
2
static class Distance {
3
int i;
4
int j;
5
double dist;
6

7
public Distance(int i, int j, double dist) {
8
this.i = i;
9
this.j = j;
10
this.dist = dist;
11
}
12
}
13

14
public int[][] kClosest(int[][] points, int k) {
15
PriorityQueue<Distance> pq = new PriorityQueue<>((x, y) -> Double.compare(x.dist, y.dist));
16
for (int[] point : points) {
17
double dist = calcDistance(point[0], point[1]);
18
pq.offer(new Distance(point[0], point[1], dist));
19
}
20
int cnt = 0;
21
ArrayList<int[]> l = new ArrayList<>();
22
while (cnt < k) {
23
Distance d = pq.poll();
24
l.add(new int[] {d.i, d.j});
25
cnt++;
26
}
27
int[][] res = l.toArray(new int[l.size()][]);
28
return res;
29
}
30

31
private double calcDistance(int i, int j) {
32
double dist = Math.sqrt(Math.pow(i, 2) + Math.pow(j, 2));
33
return dist;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0