Skip to content

Commit 1653d78

Browse files
add top K frequent elements implementation and create sample run file
1 parent 43c5379 commit 1653d78

File tree

4 files changed

+43
-1
lines changed

4 files changed

+43
-1
lines changed

26Heap/04topkfrequent.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
//O(nlogn)
4+
class Solution {
5+
public:
6+
vector<int> topKFrequent(vector<int>& arr, int k) {
7+
unordered_map<int,int> mp;
8+
for(int i=0;i<arr.size();i++){
9+
mp[arr[i]]++;
10+
}
11+
priority_queue<pair<int,int>> pq;
12+
for(const auto& ele:mp){
13+
pq.push({ele.second, ele.first});
14+
}
15+
vector<int> finalans;
16+
for(int i=1;i<=k;i++){
17+
pair<int,int> ans = pq.top();
18+
pq.pop();
19+
finalans.push_back(ans.second);
20+
}
21+
for(int ele:finalans){
22+
cout<<ele<<" ";
23+
}
24+
return finalans;
25+
}
26+
};
27+
28+
int main(){
29+
vector<int> v = {1,1,1,1,2,2,2,3};
30+
int k = 2;
31+
Solution* s1 = new Solution();
32+
s1->topKFrequent(v,2);
33+
}

26Heap/04topkfrequent.exe

263 KB
Binary file not shown.

sample.cpp

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,11 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
13
/*
2-
Simple file for doing a local run for lC questions*/
4+
Simple file for doing a local run for lC questions*/
5+
class Solution{
6+
7+
};
8+
9+
int main(){
10+
11+
}

sample.exe

123 KB
Binary file not shown.

0 commit comments

Comments
 (0)