1:题目描述
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: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
2:代码分析
方案一:最小堆方案:时间复杂度为o(nlogk)
思路:首先申请一个容器,将数字和频率放在里面,相当于一个哈希表。
然后建立一个最小堆,然后插入容器里的数,最小堆里一直存放k个频率最大的数,最后把堆里的数输出即可。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;//每次x相当于key,m【x】相当于value的值 都是int类型
cout<<m[1];//可以查看key是1的值 也就是1出现了3次
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>pq;//最小堆,保存的类型为pair类型 所以会以pair类型的第一个int类型进行排序,所以这个题目的排序方式需要用到的是频率,也就是pair.second,所以此时需要将second放在前面,不然最小堆起不到效果
for(auto p: m){//从map中提取一个元素,会得到一个pair类型的对象,pair类型的对象保存两个名为first和second的数据成员,first保存关键字 数字字,second保存value 次数
pq.push({p.second, p.first});//此时将second赋值给了pair的first,方便堆的排序 first 赋值给了second
//所以接下来在压res里面时,我们需要的是数字key,不是频率,所以需要将p的 second 压入,也就是将原来的first压入,也就是我们需要的值。
if(pq.size() > k) pq.pop();
}
vector<int>res;
while(k--) res.push_back(pq.top().second), pq.pop();
return res;
}
};
方案二:最大堆方案:时间复杂度为o(nlogn)或者o(nlogn-k)
思路: 一致
代码:
MaxHeap, O(nlogn).
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
priority_queue<pair<int, int>>pq;
for(auto p: m) pq.push({p.second, p.first});
vector<int>res;
while(k--) res.push_back(pq.top().second), pq.pop();
return res;
}
};
O(nlog(n - k)).
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
priority_queue<pair<int, int>>pq;
vector<int>res;
for(auto p: m){
pq.push({p.second, p.first});
if(pq.size() > m.size() - k){
res.push_back(pq.top().second);
pq.pop();
}
}
return res;
}
};
方案三:最优解 时间复杂度o(n)
思路:桶排序,将含有频率和数字的容器存放进桶里面,将数字出现的频率当做桶的编号,桶里面存放出现这个频率的数字。
最后从桶里面取出频率最大的k个数即可。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
vector<int>res;
vector<vector<int>>bucket(nums.size() + 1);
for(auto p: m) bucket[p.second].push_back(p.first);
for(int i = bucket.size() - 1; res.size() < k; i--)
for(auto j: bucket[i]) res.push_back(j);
return res;
}
};