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加最小堆。

需要新定义比较方法。

class Solution {
    struct cmp {
        bool operator() (const pair &a, const pair &b)
        {
            return a.second>b.second;
        }
    };
public:
    vector topKFrequent(vector& nums, int k) {
        vector ret;
        unordered_map Hash;
        for(int i=0; i,vector>,cmp> PQ;
        for(auto i = Hash.begin(); i != Hash.end(); ++i){
            if(PQ.size()!=k){
                PQ.push(*i);
            }
            else{
                if(i->second>PQ.top().second){
                    PQ.pop();
                    PQ.push(*i);
                }
            }
        }
        while(!PQ.empty()){
            ret.push_back(PQ.top().first);
            PQ.pop();
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};
stl库中有partial_sort实质上也是用堆排序完成的。

你可能感兴趣的:(LeetCode,C++)