347. Top K Frequent Elements
https://leetcode.com/problems/top-k-frequent-elements/description/
Thoughts
Code
/*
* @lc app=leetcode id=347 lang=cpp
*
* [347] Top K Frequent Elements
*/
// @lc code=start
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> freq;
const auto cmp = [](auto &a, auto &b) {
return a.first > b.first;
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
for (const auto num : nums) ++freq[num];
for (const auto &p : freq) {
pq.push({p.second, p.first});
if (pq.size() > k) {
pq.pop();
}
}
vector<int> res(k, 0);
for (int i = k - 1; i >= 0; --i) {
res[i] = pq.top().second;
pq.pop();
}
return res;
}
};
// @lc code=end
Analysis
Last updated