Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 80c4ffb

Browse files
Merge pull request #8 from joney000/priority_queue
add priority queue
2 parents f1597e6 + 52b8111 commit 80c4ffb

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

‎Algorithms/PriorityQueue.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
3+
class Point{
4+
int x, y;
5+
int distance;
6+
public Point(int x, int y){
7+
this.x = x;
8+
this.y = y;
9+
this.distance = x * x + y * y;
10+
}
11+
12+
}
13+
14+
// returns the K Closest points from origin (0, 0)
15+
// Time: O(n log k), space: O(k)
16+
public int[][] kClosest(int[][] points, int k) {
17+
if(points.length == 0 || k > points.length){
18+
return null;
19+
}
20+
int numPoints = points.length;
21+
PriorityQueue<Point> pQueue = new PriorityQueue<Point>(k + 1, (a,b) -> (b.distance - a.distance)); // max elem on top
22+
for(int[] point: points){
23+
pQueue.add(new Point(point[0], point[1]));
24+
if(pQueue.size() > k){
25+
pQueue.poll();
26+
}
27+
}
28+
int[][] sortedElements = new int[k][2];
29+
for(int pos = k - 1; pos >= 0; pos--){
30+
Point point = (Point)pQueue.poll();
31+
sortedElements[pos][0] = point.x;
32+
sortedElements[pos][1] = point.y;
33+
}
34+
return sortedElements;
35+
}
36+
}

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ In This Repository, I have written some of the important Algorithms and Data Str
4040
| [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
4141
| [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)
4242
| [LIS - Longest Increasing Subsequence](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/LIS_nLOGn.java)| O(N * log(N)), O(N)
43+
| [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)
4344

4445
## Contributions
4546

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /