Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
std::unordered_map<int, int> map;
for (auto val : nums) {
++map[val];
}
using mapiter = std::unordered_map<int, int>::iterator;
std::priority_queue<mapiter, std::vector<mapiter>, function<bool(const mapiter&,const mapiter&)>> queue(
[](const mapiter& p1, const mapiter& p2) { return p1->second > p2->second;});
for (auto it = map.begin(); it != map.end(); it++)
{
if (queue.size() < k) {
queue.push(it);
}
else if (it->second > queue.top()->second){
queue.pop();
queue.push(it);
}
}
std::vector<int> vi(k);
for (int i = k-1; i >= 0; i--)
{
auto it = queue.top();
vi[i] = it->first;
queue.pop();
}
return vi;
}
};