Skip to content

Commit

Permalink
Merge pull request #8 from joney000/priority_queue
Browse files Browse the repository at this point in the history
add priority queue
  • Loading branch information
joney000 authored Jan 1, 2022
2 parents f1597e6 + 52b8111 commit 80c4ffb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
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

0 comments on commit 80c4ffb

Please sign in to comment.