C++ solution using HashMap & Bucket Sort beat 97%


  • 0
    Z
        vector<string> topKFrequent(vector<string>& words, int k) {
            vector<string> res;
            unordered_map<string,int> m;
            for (string s:words)
                m[s]++;
            vector<set<string>> bucket(words.size()+1,set<string>{});
            for (auto it:m)
                bucket[it.second].insert(it.first);
            for (int i=words.size(); i>0; i--)
            {
                for (string s:bucket[i])
                {
                    res.push_back(s);
                    if (res.size()==k)  
                        return res;
                }
            }
            return res;
        }
    

Log in to reply
 

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