其他分享
首页 > 其他分享> > 692. 前K个高频单词

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;
    }
};

 

标签:692,right,first,单词,second,ans,minHeap,高频,left
来源: https://www.cnblogs.com/Dancing-Fairy/p/13027415.html