C++ Count and Sort, O(N*Log(N)) Time O(N) Space


  • 0
    M
    class Solution {
    public:
        vector<string> topKFrequent(vector<string>& words, int k) {
            unordered_map<string, int> cnts;
            for (auto& w: words) ++cnts[w];
            vector<pair<int, string>> interm;
            for (auto& p: cnts) interm.push_back({-p.second, p.first});
            sort(interm.begin(), interm.end());
            vector<string> result(k);
            for (int i = 0; i < k; ++i) result[i] = interm[i].second;
            return result;
        }
    };
    

Log in to reply
 

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