LeetCode347. Top K Frequent Elements

先利用map统计各数的个数,再用vector存储统计结果,自定义vector排序


class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> m;
        if(k>=nums.size()) return nums;
        map<int,int> cnt;
        for(vector<int>::iterator it=nums.begin();it!=nums.end();it++){
            cnt[*it]++;
        }
        vector<pair<int,int> > rs;
        for(map<int,int>::iterator it=cnt.begin();it!=cnt.end();it++){
            rs.push_back(*it);
        }
        sort(rs.begin(),rs.end(),[&](pair<int,int> a,pair<int,int> b){return a.second > b.second;});
        int i=0;
        for(vector<pair<int,int> >::iterator it=rs.begin();it!=rs.end(),i!=k;++it,++i){
            m.push_back(it->first);
        }
        return m;
    }
};


你可能感兴趣的:(LeetCode347. Top K Frequent Elements)