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].

解法1:利用map和桶排序,算法复杂度$$O(n)$$

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> frequence;

        for(auto n:nums)
            frequence[n]++;

        vector<vector<int> > buckets(nums.size() + 1);

        for(auto it = frequence.begin(); it != frequence.end(); ++it){
            buckets[it->second].push_back(it->first);
        }
        reverse(buckets.begin(), buckets.end());
        vector<int> res;
        for(auto &bucket:buckets){
            for(auto &n:bucket){
                res.push_back(n);
                if(res.size() == k) return res;
            }
        }
        return res;
    }
};

解法2:利用map+最大堆的性质

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> frequence;
        for(auto n:nums)
            frequence[n]++;

        typedef pair<int, int> P;
        priority_queue<P> pq;
        vector<int> res;
        for(auto it = frequence.begin(); it != frequence.end(); ++it){
            pq.push(make_pair(it->second, it->first));

            if(pq.size() > (int)frequence.size() - k){
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};

results matching ""

    No results matching ""