Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output:
Example 2:

Input: nums = [1], k = 1
Output:
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.
题目是求一组序列中出现频率最高的k个数,这里有个前提是k是合法的(大于1小于出现的不同值个数)
非常容易想到使用优先队列:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> map;
        for(int num : nums){
            map[num]++;
        }
        
        vector<int> res;
        // pair<first, second>: first is frequency,  second is number
        priority_queue<pair<int,int>> pq; 
        for(auto it = map.begin(); it != map.end(); it++){
            pq.push(make_pair(it->second, it->first));
        }
        
        for(int i = 0;i < k;i++)
        {
            res.push_back(pq.top().second);
            pq.pop();
        }
        
        return res;
    }
};

在讨论区看到大神的代码,最后的循环其实可以去掉,因为这里求的最大的K个元素无需按照元素大小排序,当未参与构建最大堆的元素不足k个时,优先队列top元素必定是TOP k元素。

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> map;
        for(int num : nums){
            map[num]++;
        }
        
        vector<int> res;
        // pair<first, second>: first is frequency,  second is number
        priority_queue<pair<int,int>> pq; 
        for(auto it = map.begin(); it != map.end(); it++){
            pq.push(make_pair(it->second, it->first));
            if(pq.size() > map.size() - k)
            {
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        
        
        return res;
    }
};

另一种方法是使用std::nth_element

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
    std::unordered_map<int, int> freq;
    std::vector<int> ret;
    for (auto n : nums) 
    {
        if(1 == ++freq[n])
        {
            ret.push_back(n);
        }
    }

    std::nth_element(ret.begin(), ret.begin() + k - 1, ret.end(), [&freq] (int l, int r) -> bool {
        return freq[l] > freq[r];
      });
    ret.resize(k);
    return ret;
  }
};