Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite8fbafd

Browse files
Create 973-K-Closest-Points-to-Origin.java
1 parentd441768 commite8fbafd

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+
classSolution {
5+
publicint[][]kClosest(int[][]points,intk) {
6+
HashMap<int[],Double>map =newHashMap<>();
7+
PriorityQueue<Map.Entry<int[],Double>>pq =newPriorityQueue<>((a,b)->Double.compare(a.getValue(),b.getValue()));
8+
for (inti =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.Entryset:map.entrySet()) {
12+
pq.add(set);
13+
}
14+
int[][]ans =newint[k][2];
15+
for (inti =0;i<k;i++) {
16+
int[]temp =pq.poll().getKey();
17+
ans[i][0] =temp[0];
18+
ans[i][1] =temp[1];
19+
}
20+
returnans;
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+
classSolution {
28+
publicint[][]kClosest(int[][]points,intk) {
29+
HashMap<int[],Integer>map =newHashMap<>();
30+
PriorityQueue<Map.Entry<int[],Integer>>pq =newPriorityQueue<>((a,b)->a.getValue()-b.getValue());
31+
for (inti =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.Entryset:map.entrySet()) {
35+
pq.add(set);
36+
}
37+
int[][]ans =newint[k][2];
38+
for (inti =0;i<k;i++) {
39+
int[]temp =pq.poll().getKey();
40+
ans[i][0] =temp[0];
41+
ans[i][1] =temp[1];
42+
}
43+
returnans;
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp