347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

给出一个不为空的整数数组,返回出现频率前k位的数字。

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. //你可以假设k总是有效的。
    • Your algorithm's time complexity must be better than O(n log n), where n is the array's size. //你算法复杂度必须比O(nlogn)更好。

1、考虑使用map,但是时间会超出,改用没有顺序的unordered_map。

2、使用优先队列,找出出现频率前k位的数。

注意:下面给出的算法得出的结果并没有严格的排序,比如2出现的次数比3多,但是在res中,可能3排在2前面。

 1 class Solution {
 2 public:
 3     vector<int> topKFrequent(vector<int>& nums, int k) {
 4         unordered_map<int,int> map;
 5         for(int num : nums){
 6             map[num]++;
 7         }
 8         
 9         vector<int> res;
10         priority_queue<pair<int,int>> pq; 
11         for(auto it = map.begin(); it != map.end(); it++){
12             pq.push(make_pair(it->second, it->first));
13             if(pq.size() > (int)map.size() - k){
14                 res.push_back(pq.top().second);
15                 pq.pop();
16             }
17         }
18         return res;
19     }
20 };
原文地址:https://www.cnblogs.com/Z-Sky/p/5655479.html