diff --git a/Top K Frequent Elements b/Top K Frequent Elements new file mode 100644 index 0000000..c11763f --- /dev/null +++ b/Top K Frequent Elements @@ -0,0 +1,18 @@ +vector topKFrequent(vector& nums, int k) { + unordered_map map; + for(int num : nums){ + map[num]++; + } + + vector res; + // pair: first is frequency, second is number + priority_queue> pq; + for(auto it = map.begin(); it != map.end(); it++){ + pq.push(make_pair(it->second, it->first)); + if(pq.size() > (int)map.size() - k){ + res.push_back(pq.top().second); + pq.pop(); + } + } + return res; + }