leetcode 347. Top K Frequent Elements

用优先队列排序,优先队列是大根堆

 

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> result;
        int length = nums.size();
        if(length <= 0)
            return result;
        unordered_map<int,int> m;
        priority_queue<pair<int,int>> n;
        for(auto a : nums)
            m[a]++;
        for(auto a : m)
            n.push({a.second,a.first});
        for(int i = 0;i < k;i++){
            result.push_back(n.top().second);
            n.pop();
        }
        return result;
    }
};

https://www.cnblogs.com/grandyang/p/5454125.html

posted @ 2018-09-16 22:55  有梦就要去实现他  阅读(254)  评论(0编辑  收藏  举报