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;
    }
};
上一篇:必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】


下一篇:接口mock实战1+2