C++: Without define another comparison function O(nlogk)


  • 0
    X
    class Solution {
    public:
        vector<string> topKFrequent(vector<string>& words, int k) {
            vector<string> ret;
            unordered_map<string, int> m;
            priority_queue<pair<int, string>> pq;
            for (auto &&s : words) --m[s];
            for (auto &&p : m) {
                pq.emplace(p.second, p.first);
                if (pq.size() > k) pq.pop();
            }
            ret.resize(pq.size());
            for (int i = pq.size() - 1; i >= 0; --i) {
                ret[i] = pq.top().second;
                pq.pop();
            }
            return ret;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.