class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
priority_queue<pair<int, int>> pq;
vector<int> res;
for (int num : nums) {
m[num]++;
}
for (auto it : m) {
pq.push({it.second, it.first});
}
for (int i = 0; i < k; ++i) {
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> hm;
for (auto num : nums)
hm[num]++;
priority_queue<pair<int, int>> pq;
vector<int> res;
int n = hm.size();
for (auto it = hm.begin(); it != hm.end(); ++it) {
pq.push(make_pair(it->second, it->first));
if (pq.size() > n - k) {
res.push_back(pq.top().second);
pq.pop();
}
}
return res;
}
};