[C++] A Short Solution Using MAPs


  • 0
    A
    class Solution {
    public:
        using pos = vector<int>::size_type;
        vector<int> topKFrequent(vector<int>& nums, int k) {
            vector<int> result;
            unordered_map<int, int> nums_cnt;
            multimap<int, int> cnt_nums;
            for(pos i = 0; i < nums.size(); ++i)
                ++nums_cnt[nums[i]];
            for(auto it = nums_cnt.begin(); it != nums_cnt.end(); ++it)
                cnt_nums.insert((make_pair(it->second, it->first)));
            pos i = 0;
            for(auto it = cnt_nums.rbegin(); i < k ; ++it, ++i)
                result.push_back(it->second);
            return result;
        }
    };

  • 1
    Q

    This is not better than O(nlogn)


  • 0
    A

    Talk is CHEAP, so show me your calculation.


Log in to reply
 

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