[LeetCode] Top K Frequent Elements

347. Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
vector<int> res(k);
for(auto& num : nums) {
m[num]++;
}
priority_queue<pair<int, int>> pq;
for(auto& elem : m) {
pq.push({elem.second, elem.first});
}
while(k--) {
res[k] = pq.top().second;
pq.pop();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/05/PS/LeetCode/top-k-frequent-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.