Skip to content

Commit e8fbafd

Browse files
Create 973-K-Closest-Points-to-Origin.java
1 parent d441768 commit e8fbafd

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//Both solutions use same Idea
2+
//Time complexity O(Nlogk)
3+
4+
class Solution {
5+
public int[][] kClosest(int[][] points, int k) {
6+
HashMap<int[], Double> map = new HashMap<>();
7+
PriorityQueue<Map.Entry<int[], Double>> pq = new PriorityQueue<>((a,b)->Double.compare(a.getValue(),b.getValue()));
8+
for (int i = 0; i<points.length; i++) {
9+
map.put(points[i], Math.pow((Math.pow(points[i][0], 2)+Math.pow(points[i][1], 2)), 0.5));//We can also ignore this rooting as I did in the next solution
10+
}
11+
for (Map.Entry set: map.entrySet()) {
12+
pq.add(set);
13+
}
14+
int[][] ans = new int[k][2];
15+
for (int i = 0; i<k; i++) {
16+
int[] temp = pq.poll().getKey();
17+
ans[i][0] = temp[0];
18+
ans[i][1] = temp[1];
19+
}
20+
return ans;
21+
}
22+
}
23+
24+
//Since, we need to find the minimum, it doens't matter if we square root them. As the minimum will remain the same after square rooting also.
25+
//Ex: 4.8<4.9 -> root(4.8)<root(4.9)
26+
27+
class Solution {
28+
public int[][] kClosest(int[][] points, int k) {
29+
HashMap<int[], Integer> map = new HashMap<>();
30+
PriorityQueue<Map.Entry<int[], Integer>> pq = new PriorityQueue<>((a,b)->a.getValue()-b.getValue());
31+
for (int i = 0; i<points.length; i++) {
32+
map.put(points[i], (int)(Math.pow(points[i][0], 2)+Math.pow(points[i][1], 2)));
33+
}
34+
for (Map.Entry set: map.entrySet()) {
35+
pq.add(set);
36+
}
37+
int[][] ans = new int[k][2];
38+
for (int i = 0; i<k; i++) {
39+
int[] temp = pq.poll().getKey();
40+
ans[i][0] = temp[0];
41+
ans[i][1] = temp[1];
42+
}
43+
return ans;
44+
}
45+
}

0 commit comments

Comments
 (0)