347. Top K Frequent Elements

来源:互联网 发布:单片机乐谱编辑软件 编辑:程序博客网 时间:2024/06/07 14:26
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        
          unordered_map<int,int> map;  
        for(int num : nums){  
            map[num]++;  
        }  
          
        vector<int> res;  
       
        priority_queue<pair<int,int>> 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;  
    }  
}; 
原创粉丝点击