Skip to content

Instantly share code, notes, and snippets.

@ahmedeltaher
Created October 3, 2021 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedeltaher/cbdd326ddd9dce9aa9dea0f1950da504 to your computer and use it in GitHub Desktop.
Save ahmedeltaher/cbdd326ddd9dce9aa9dea0f1950da504 to your computer and use it in GitHub Desktop.
973. K Closest Points to Origin
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