forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0973-k-closest-points-to-origin.java
57 lines (52 loc) · 1.9 KB
/
0973-k-closest-points-to-origin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//First solution Time Complexity is O(NlogN)
//Just take a min heap and add the values using the formula and return the top k values
//We can completely ignore the square root as we are just comparing the values (if a*a>b*b => a>b)
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) ->
Integer.compare(
(a[0] * a[0] + a[1] * a[1]),
(b[0] * b[0] + b[1] * b[1])
)
);
for (int[] point : points) {
q.add(point);
}
int[][] ans = new int[k][2];
for (int i = 0; i < k; i++) {
int[] cur = q.poll();
ans[i][0] = cur[0];
ans[i][1] = cur[1];
}
return ans;
}
}
//This approach is a sightly optimized approach here we can use a max heap and maintain its size as k.
//So when we do the removal the time complexity will reduce from logn to logk
//Max heap because we will remove the top elements (the one which are greater)
//Overall Time complexity O(NlogK)
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) ->
Integer.compare(
(b[0] * b[0] + b[1] * b[1]),
(a[0] * a[0] + a[1] * a[1])
)
); //only this is changed (swapped)
for (int[] point : points) {
q.add(point);
//remove when size increase k
if (q.size() > k) {
q.remove();
}
}
int[][] ans = new int[k][2];
for (int i = 0; i < k; i++) {
int[] cur = q.poll();
ans[i][0] = cur[0];
ans[i][1] = cur[1];
}
return ans;
}
}
//There are also some O(N) solutions using quick select and binary search https://leetcode.com/problems/k-closest-points-to-origin/solution/