LeetCode.692

  需要注意如果频率相同则按字典序排序:

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> f;
        for (auto w: words)
            f[w] += 1;
        auto cmp = [](pair<string, int> a, pair<string, int> b)
        {
            if (a.second == b.second)
                return a.first > b.first;
            return a.second < b.second;
        };
        priority_queue<pair<string, int>, vector<pair<string, int>>,
            decltype(cmp)> q(cmp);
        for (auto i: f)
            q.push(i);
        vector<string> s;
        while (k--)
        {
            s.push_back(q.top().first);
            q.pop();
        }
        return s;
    }
};

  

原文地址:https://www.cnblogs.com/darkchii/p/13580000.html