Posted on

Description

Submission

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int, int> m;
        for(int i = 0; i < nums.size(); ++i) {
            auto iter = m.find(nums[i]);
            if(iter == m.end()) m.insert(make_pair(nums[i], 1));
            else m[nums[i]]++;
        }
        vector<pair<int, int>> v(m.begin(), m.end());
        sort(v.begin(), v.end(), [](pair<int, int>& p1, pair<int, int>& p2){return p1.second > p2.second;});
        vector<int> res;
        for(int i = 0; i < k; ++i) {
            res.push_back(v[i].first);
        }
        return res;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *