其他分享
首页 > 其他分享> > 优先队列——heap

优先队列——heap

作者:互联网

347. 前 K 个高频元素

priority_queue<Type, Container, Functional> // greater<>表示小根堆

vector<int> topKFrequent(vector<int>& nums, int k) {
        priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> minHeap;
        unordered_map<int,int> count;
        for(int i : nums){
            ++count[i];
        }
        for(auto& x:count){
            auto pair = make_pair(x.second, x.first);
            if(minHeap.size()==k){
                if(pair < minHeap.top()) continue;
                minHeap.pop();
            }
            minHeap.push(move(pair));
        }
        vector<int> ans(k,0);
        while(!minHeap.empty()){
            ans[--k]=minHeap.top().second;
            minHeap.pop();
        }
        return ans;
    }

 

标签:count,优先,队列,pop,vector,heap,ans,pair,minHeap
来源: https://www.cnblogs.com/Dancing-Fairy/p/12725606.html