Skip to content

Commit 76898e3

Browse files
add 973
1 parent 0ad1eab commit 76898e3

File tree

2 files changed

+39
-9
lines changed

2 files changed

+39
-9
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_973.java

+26
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,30 @@ private double getDistance(int[] point) {
3636
return Math.sqrt(Math.pow(point[0], 2) + Math.pow(point[1], 2));
3737
}
3838
}
39+
40+
public static class Solution2 {
41+
public int[][] kClosest(int[][] points, int k) {
42+
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> (b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1]));
43+
for (int[] point : points) {
44+
long distance = (long) point[0] * point[0] + point[1] * point[1];
45+
if (maxHeap.size() < k) {
46+
maxHeap.offer(point);
47+
} else {
48+
int[] peek = maxHeap.peek();
49+
long peekedDistance = (long) peek[0] * peek[0] + peek[1] * peek[1];
50+
if (peekedDistance > distance) {
51+
//this is an optimization so that the space complexity is limited to O(k)
52+
maxHeap.poll();
53+
maxHeap.offer(point);
54+
}
55+
}
56+
}
57+
int[][] result = new int[k][2];
58+
for (int i = 0; i < k; i++) {
59+
int[] point = maxHeap.poll();
60+
result[i] = point;
61+
}
62+
return result;
63+
}
64+
}
3965
}

Diff for: src/test/java/com/fishercoder/_973Test.java

+13-9
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
package com.fishercoder;
22

33
import com.fishercoder.solutions._973;
4-
import org.junit.BeforeClass;
5-
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
66

7-
import static org.junit.Assert.assertArrayEquals;
7+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
88

99
public class _973Test {
10-
private static _973.Solution1 test;
10+
private static _973.Solution1 solution1;
11+
private static _973.Solution2 solution2;
1112

12-
@BeforeClass
13-
public static void setUp() {
14-
test = new _973.Solution1();
13+
@BeforeEach
14+
public void setUp() {
15+
solution1 = new _973.Solution1();
16+
solution2 = new _973.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
19-
assertArrayEquals(new int[][]{{-2, 2}}, test.kClosest(new int[][]{{1, 3}, {-2, 2}}, 1));
21+
assertArrayEquals(new int[][]{{-2, 2}}, solution1.kClosest(new int[][]{{1, 3}, {-2, 2}}, 1));
22+
assertArrayEquals(new int[][]{{-2, 2}}, solution2.kClosest(new int[][]{{1, 3}, {-2, 2}}, 1));
2023
}
2124

2225
@Test
2326
public void test2() {
24-
assertArrayEquals(new int[][]{{3, 3},{-2, 4}}, test.kClosest(new int[][]{{3, 3},{5, -1},{-2, 4}}, 2));
27+
assertArrayEquals(new int[][]{{3, 3}, {-2, 4}}, solution1.kClosest(new int[][]{{3, 3}, {5, -1}, {-2, 4}}, 2));
28+
assertArrayEquals(new int[][]{{-2, 4}, {3, 3}}, solution2.kClosest(new int[][]{{3, 3}, {5, -1}, {-2, 4}}, 2));
2529
}
2630
}

0 commit comments

Comments
 (0)