I am wondering why people don't share out the O(nlogk) solution. Keep a max heap has size K. This in principle will be closed to O(n) since logk is a constant.

```
using Pair = pair<int, int>;
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int num : nums){
map[num]++;
}
vector<int> res;
// pair<first, second>: first is frequency, second is number
priority_queue<Pair, vector<Pair>, greater<Pair>> pq;
for(auto it = map.begin(); it != map.end(); it++){
pq.push(make_pair(it->second, it->first));
if(pq.size() > k) pq.pop();
}
while(!pq.empty()) {
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
```