Skip to content

Commit 64d0880

Browse files
PDKhanriver20s
authored andcommitted
top-k-frequent-elements solution
1 parent 70ae377 commit 64d0880

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

top-k-frequent-elements/PDKhan.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
vector<int> topKFrequent(vector<int>& nums, int k) {
4+
unordered_map<int, int> map;
5+
vector<int> result;
6+
7+
for(int i = 0; i < nums.size(); i++){
8+
map[nums[i]]++;
9+
}
10+
11+
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> minHeap;
12+
13+
for(auto i : map){
14+
minHeap.push({i.second, i.first});
15+
if(minHeap.size() > k)
16+
minHeap.pop();
17+
}
18+
19+
while(!minHeap.empty()){
20+
result.push_back(minHeap.top().second);
21+
minHeap.pop();
22+
}
23+
24+
return result;
25+
}
26+
};

0 commit comments

Comments
 (0)