Skip to content

add priority queue #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Algorithms/PriorityQueue.java
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;
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ In This Repository, I have written some of the important Algorithms and Data Str
| [Kth Order Statics](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/kthOrderStatics.java)|O(N), O(N) | K’th Smallest/Largest Element in Unsorted Array
| [Trie / Prefix Tree](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/Trie.java)| O(N * L), O(N * L)| if there are N strings of L size, per query time(Prefix information) = O(L)
| [LIS - Longest Increasing Subsequence](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/LIS_nLOGn.java)| O(N * log(N)), O(N)
| [Priority Queue](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/PriorityQueue.java)| O(log(N)), O(N) | N = no of objects in the queue. peek: O(1), poll/add: O(log n)

## Contributions

Expand Down