Top K Frequent Words(C++前K个高频单词)

参考网址:https://leetcode.com/problems/top-k-frequent-words/discuss/108366/O(nlog(k))-Priority-Queue-C%2B%2B-code

解题思路:

(1)使用unordered_map的键值对来存储字符串和对应出现的次数

(2)再重写priority_queue(优先队列)的比较函数,将优先级较大的放在队首,依次取前k个即可



class Solution {
public:
    
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> freq;
        for(auto w : words){
            freq[w]++;
        }
    
        auto comp = [&](const pair<string,int>& a, const pair<string,int>& b) {
    	    //return true if b is considered to go top a
            return a.second < b.second || (a.second == b.second && a.first > b.first); 
        };
        priority_queue< pair<string,int>, vector<pair<string,int>>, decltype(comp) > pq(freq.begin(),freq.end(),comp);
    
    
        vector<string> output;
    
        while(k!=0){
            output.push_back(pq.top().first);
            pq.pop();
            k--;
        }
        return output;
    }
};
发布了264 篇原创文章 · 获赞 272 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105450156