Simple C++


  • 0
    G
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int, int> num_f; // number -> frequency
            for (int i = 0; i < nums.size(); i++) {
                num_f[nums[i]]++;
            }
            multimap<int, int> freq_nums; // frequency -> numbers
            for (unordered_map<int, int>::iterator it = num_f.begin(); it != num_f.end(); it++) {
                pair<int, int> p(it->second, it->first);
                freq_nums.insert(p);
            }
            vector<int> r;
            for (multimap<int, int>::reverse_iterator it = freq_nums.rbegin(); k > 0; it++, k--) {
                r.push_back(it->second);
            }
            return r;
        }
    

Log in to reply
 

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