其他分享
首页 > 其他分享> > leetcode 692. 前K个高频单词 (百度)2021-08-03

leetcode 692. 前K个高频单词 (百度)2021-08-03

作者:互联网

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

class Solution {
public:
    class cmp
    {
    public:
        bool operator()(const pair<string, int>& lhs, const pair<string, int>& rhs)
        {
            return lhs.second == rhs.second ? lhs.first < rhs.first : lhs.second > rhs.second;//注意这个地方,出现频率相同按字母排序
            // return lhs.second > rhs.second;
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) 
    {
        unordered_map<string, int> mp;
        for (auto& x: words)
        {
            mp[x]++;
        }
        //小顶堆 priority_queue
        priority_queue<pair<string, int>, vector<pair<string, int>>, cmp> prq;
        for (auto& y : mp)
        {
            // prq.emplace(y);
            prq.push(y);
            if (prq.size() > k)
                prq.pop();
        }

        vector<string> res(k);
        for (int i = k - 1; i >= 0; i--)
        {
            res[i] = prq.top().first;
            prq.pop();
        }
        return res;
    }
};

标签:692,03,res,08,second,vector,prq,lhs,rhs
来源: https://blog.csdn.net/sususuqingxiao/article/details/119361567