C++ AC Solution. Not fastest but short


  • 0
    class Solution {
    public:
        vector<string> topKFrequent(vector<string>& words, int k) {
            vector<string> res;
            unordered_map<string, int> cnt;
            for (auto &s : words) {
                if (cnt[s]++ == 0)
                    res.push_back(s);
            }        
            sort(res.begin(), res.end(), [&](const string& s1, const string& s2) {
               return cnt[s1] == cnt[s2] ? s1 < s2 : cnt[s1] > cnt[s2]; 
            });
            res.resize(k);
            return res;
        }
    };
    

Log in to reply
 

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