问题描述
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.
思路分析
给一数组,返回前k个出现次数最多的元素。
这是一道非常经典的题目,在微软的面试中被问到,这是道follow-up起来非常有意思的题目。
首先要统计数组中每个元素出现的频率,用一个map来保存,然后将频率和元素make_pair,放进priority_queue中,将前k个元素输出即可。
代码
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
for (auto n : nums){
map[n]++;
}
vector<int> res;
priority_queue<pair<int, int>> qp;
//second is frequency, first is num
for (auto it = map.begin(); it != map.end(); it++){
qp.push(make_pair(it->second, it->first));
if (qp.size() > (int)map.size() - k){
res.push_back(qp.top().second);
qp.pop();
}
}
return res;
}
};
时间复杂度:
O(nlog(n−k))
O
(
n
l
o
g
(
n
−
k
)
)
空间复杂度:
O(n)
O
(
n
)
反思
要注意的是map用的是指针表示映射前后的值,而make_pair之后则是直接调用对象属性的操作方式。priority queue使用的是最小堆,时间复杂度是 O(logn) O ( l o g n ) 的,因为只需要保存n-k个元素,所以时间复杂度如上所示。
如果不这么复杂的话,可以直接使用排序的方式,C++内部使用的排序算法是快速排序, O(nlogn) O ( n l o g n ) 的时间复杂度。
follow-up:
如果数组中的元素种类较少时,比如数字范围在[1-1000],我们可以使用桶排序,可以实现
O(n)
O
(
n
)
的时间复杂度。
思想是在统计了每个数字出现的频率之后,将频率由高到低存放在桶中。因为用n个元素,而每种元素都不相同时,我们需要的桶的大小为nums.size() + 1(因为不会有出现次数为0的元素,同样后面统计的循环也是这样)。将对应频率的数字放到对应的桶中去(也可以用一个hash table映射的),然后从大到小输出到res数组中即可。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
vector<vector<int>> buckets(nums.size() + 1);
vector<int> res;
for(int n : nums){
map[n]++;
}
for(auto it : map){
buckets[it.second].push_back(it.first);
}
for(int i = nums.size(); i >= 0; i--){
for(int j = 0; j < buckets[i].size(); j++){
res.push_back(buckets[i][j]);
if(res.size() == k) return res;
}
}
return res;
}
};