Skip to content

Commit 572d2ec

Browse files
refactor 973
1 parent de46123 commit 572d2ec

File tree

1 file changed

+44
-14
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+44
-14
lines changed

src/main/java/com/fishercoder/solutions/_973.java

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,63 @@
33
import java.util.Comparator;
44
import java.util.PriorityQueue;
55

6+
/**
7+
* 973. K Closest Points to Origin
8+
*
9+
* We have a list of points on the plane. Find the K closest points to the origin (0, 0).
10+
*
11+
* (Here, the distance between two points on a plane is the Euclidean distance.)
12+
*
13+
* You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
14+
*
15+
*
16+
*
17+
* Example 1:
18+
*
19+
* Input: points = [[1,3],[-2,2]], K = 1
20+
* Output: [[-2,2]]
21+
* Explanation:
22+
* The distance between (1, 3) and the origin is sqrt(10).
23+
* The distance between (-2, 2) and the origin is sqrt(8).
24+
* Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
25+
* We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
26+
* Example 2:
27+
*
28+
* Input: points = [[3,3],[5,-1],[-2,4]], K = 2
29+
* Output: [[3,3],[-2,4]]
30+
* (The answer [[-2,4],[3,3]] would also be accepted.)
31+
*
32+
*
33+
* Note:
34+
*
35+
* 1 <= K <= points.length <= 10000
36+
* -10000 < points[i][0] < 10000
37+
* -10000 < points[i][1] < 10000
38+
* */
639
public class _973 {
740

841
public static class Solution1 {
942
public int[][] kClosest(int[][] points, int K) {
1043
int[][] ans = new int[K][2];
1144

12-
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
13-
@Override
14-
public int compare(int[] o1, int[] o2) {
15-
double dist1 = getDistance(o1);
16-
double dist2 = getDistance(o2);
17-
18-
if (dist1 > dist2) {
19-
return 1;
20-
} else if (dist1 < dist2) {
21-
return -1;
22-
} else {
23-
return 0;
24-
}
45+
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> {
46+
double dist1 = getDistance(o1);
47+
double dist2 = getDistance(o2);
48+
49+
if (dist1 > dist2) {
50+
return 1;
51+
} else if (dist1 < dist2) {
52+
return -1;
53+
} else {
54+
return 0;
2555
}
2656
});
2757

2858
for (int[] point : points) {
2959
pq.add(point);
3060
}
3161

32-
for (int i=0; i<K; i++) {
62+
for (int i = 0; i < K; i++) {
3363
ans[i] = pq.poll();
3464
}
3565

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy