-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from joney000/priority_queue
add priority queue
- Loading branch information
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
class Solution { | ||
|
||
class Point{ | ||
int x, y; | ||
int distance; | ||
public Point(int x, int y){ | ||
this.x = x; | ||
this.y = y; | ||
this.distance = x * x + y * y; | ||
} | ||
|
||
} | ||
|
||
// returns the K Closest points from origin (0, 0) | ||
// Time: O(n log k), space: O(k) | ||
public int[][] kClosest(int[][] points, int k) { | ||
if(points.length == 0 || k > points.length){ | ||
return null; | ||
} | ||
int numPoints = points.length; | ||
PriorityQueue<Point> pQueue = new PriorityQueue<Point>(k + 1, (a,b) -> (b.distance - a.distance)); // max elem on top | ||
for(int[] point: points){ | ||
pQueue.add(new Point(point[0], point[1])); | ||
if(pQueue.size() > k){ | ||
pQueue.poll(); | ||
} | ||
} | ||
int[][] sortedElements = new int[k][2]; | ||
for(int pos = k - 1; pos >= 0; pos--){ | ||
Point point = (Point)pQueue.poll(); | ||
sortedElements[pos][0] = point.x; | ||
sortedElements[pos][1] = point.y; | ||
} | ||
return sortedElements; | ||
} | ||
} |
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