692. Top K Frequent Words

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了692. Top K Frequent Words相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/top-k-frequent-words/description/

class ComparisonClass {
public:
    bool operator() (pair<int,string> p1, pair<int,string> p2) {
        return p1.first < p2.first || p1.first == p2.first && p1.second > p2.second;
    }
};
class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int> freq;
        for (const auto& w : words)
            freq[w]++;
        priority_queue<pair<int,string>, vector<pair<int,string>>, ComparisonClass> q;
        for (const auto& f : freq)
            q.push( { f.second, f.first });
        
        vector<string> res;
        while (k-- > 0 && !q.empty()) {
            res.push_back(q.top().second);
            q.pop();
        }
        return res;
    }
};

 

以上是关于692. Top K Frequent Words的主要内容,如果未能解决你的问题,请参考以下文章

347. Top K Frequent Elements/692. Top K Frequent Words

692. Top K Frequent Words

692. Top K Frequent Words

692. Top K Frequent Words

***Leetcode 692. Top K Frequent Words

Leetcode 692: Top K Frequent Words