优先队列--著名的TopK问题(最小堆的使用)

692. Top K Frequent Words

Medium

77671FavoriteShare

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

 

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.
class Solution {
    
public:
    inline bool Cmp1(const pair& a1,const pair& a2){
        if(a1.first > a2.first){
            return true;
        }
        if(a1.first == a2.first && a1.second < a2.second){
            return true;
        }
        return false;
    }
    struct Cmp{
        bool operator ()(const pair& a1,const pair& a2){
            if(a1.first > a2.first){
                return true;
            }
            if((a1.first == a2.first) && (a1.second < a2.second)){
                return true;
            }
            return false;
        }
    };
    vector topKFrequent(vector& words, int k) {
        unordered_map HashMap;
        priority_queue,vector>,Cmp> Q;
        vector Result;
        int cnt = 0;
        for(auto word : words){
            HashMap[word] ++;
        }
        for(auto i : HashMap){
            pair tmp= make_pair(i.second,i.first);
            if(cnt < k){
                Q.push(tmp);
                cnt++;
            }
            else{
                if(Cmp1(tmp,Q.top())){
                    Q.push(tmp);
                    Q.pop();
                }
            }
        }
        while(!Q.empty()){
            pair tmp = Q.top();
            Result.push_back(tmp.second);
            Q.pop();
        }
        reverse(Result.begin(),Result.end());
        return Result;
    }
};

 

你可能感兴趣的:(优先队列--著名的TopK问题(最小堆的使用))