C++ map and multimap easy understand


  • 1
    Y
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            vector<int> ret;
            map<int, int> mp1;  //mp1 : first is key , second is frequent
            //mp2 : first is frequent, second is key
            multimap<int, int, std::greater<int>> mp2; // key can be  repetition
            for (auto it : nums) {
                mp1[it]++;
            }
            for (auto it : mp1) {
                mp2.insert(make_pair(it.second, it.first));
            }
            for (auto it : mp2) {
                ret.push_back(it.second);
                k--;
                if (!k) break;
            }
            return ret;
        }
    };
    

Log in to reply
 

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