Skip to content

Commit 7ac9f01

Browse files
Create Top K elements Priority_queue.cpp
1 parent 997121e commit 7ac9f01

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Top K elements Priority_queue.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void topKElements(const vector<int>& nums, int k) {
5+
//priority_queue<int> maxHeap;
6+
// OR
7+
// priority_queue<int, vector<int>, less<int>> maxHeap;
8+
9+
priority_queue<int, vector<int>, greater<int>> minHeap;
10+
11+
for (int num : nums) {
12+
minHeap.push(num);
13+
if (minHeap.size() > k) {
14+
minHeap.pop(); // remove the smallest
15+
}
16+
}
17+
18+
19+
while (!minHeap.empty()) {
20+
cout << minHeap.top() <<endl;
21+
minHeap.pop();
22+
}
23+
24+
}
25+
26+
int main() {
27+
vector<int> nums = {4, 1, 7, 3, 9, 2, 6};
28+
int k = 3;
29+
30+
cout << "Top " << k << " elements are: "<<endl;
31+
topKElements(nums, k);
32+
33+
34+
35+
return 0;
36+
}
37+
/*
38+
Top 3 elements are:
39+
6
40+
7
41+
9
42+
*/

0 commit comments

Comments
 (0)