692. 前K个高频单词

692. 前K个高频单词

涉及到一个自定义heap

struct cmp{
    template<typename T, typename U>
    bool operator()(T const& left, U const& right){
        if(left.second>right.second||(left.second==right.second&&left.first<right.first))
            return true;
        return false;
    }
};

priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> minHeap;

代码如下:

class Solution {
public:
struct cmp{
    template<typename T, typename U>
    bool operator()(T const& left, U const& right){
        if(left.second>right.second||(left.second==right.second&&left.first<right.first))
            return true;
        return false;
    }
};
    vector<string> topKFrequent(vector<string>& words, int k) {
        priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> minHeap;
        unordered_map<string, int> mp;
        for(string& s:words)
            mp[s]++;
        for(auto& item:mp){
            if(minHeap.size()<k){
                minHeap.push(make_pair(item.first,item.second));
            }
            else if(item.second>=minHeap.top().second){
                if(item.second==minHeap.top().second&&item.first>=minHeap.top().first)continue;
                minHeap.pop();
                minHeap.push(make_pair(item.first,item.second));
            }
        }
        vector<string> ans;
        while(!minHeap.empty()){
            ans.push_back(minHeap.top().first);
            minHeap.pop();
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

 

上一篇:构建最优二叉树


下一篇:最小堆建立哈夫曼树及各种操作