347 Top K Frequent Elements 前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
例如,
给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。
注意:
    你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。
    你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
详见:https://leetcode.com/problems/top-k-frequent-elements/description/
C++:

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

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

原文地址:https://www.cnblogs.com/xidian2014/p/8836478.html