347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
【思路】插入map后将map 转存入一个类型位pair中的vector中,再重写sort函数,按value值排序

class Solution {
public:
    struct CmpByValue {
        bool operator()(const pair<int,int>& lhs, const pair<int,int>& rhs) {
            return lhs.second > rhs.second;
  }
};
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> vc;
        map<int, int>m;
        map<int, int>m2;
        int i = 0;
        if(nums.size()==0) return vc;
        for(; i< nums.size(); i++)
        {
               m[nums[i]]++;
        }
        vector<pair<int,int>> vct(m.begin(), m.end());
        sort(vct.begin(), vct.end(), CmpByValue());
        for(int j =0; j <k; j++)
        {
            vc.push_back(vct[j].first);
        }
        return vc;
    }
};


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