Created
October 3, 2021 16:49
-
-
Save ahmedeltaher/cbdd326ddd9dce9aa9dea0f1950da504 to your computer and use it in GitHub Desktop.
973. K Closest Points to Origin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int[][] kClosest(int[][] points, int k) { | |
int [][] res = new int[k][2]; | |
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(points.length, | |
new Comparator<int[]>(){ | |
@Override | |
public int compare(int[] o1, int[]o2){ | |
double d1 = distance(o1); | |
double d2 = distance(o2); | |
if(d1==d2) return 0; | |
else if(d1>d2) return 1; | |
else return -1; | |
} | |
}); | |
for(int[] point : points){ | |
maxHeap.add(point); | |
} | |
for(int i=0; i<k ;i++){ | |
res[i] = maxHeap.poll(); | |
} | |
return res; | |
} | |
private double distance(int [] point){ | |
return Math.sqrt((point[0]*point[0]) + (point[1]*point[1])); | |
} | |
} | |
// Time ==> O(NlogN) | |
// space ==> O(N) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment