347. Top K Frequent Elements
Description:
Given a non-empty array of integers, return the k most frequent elements.
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.
Difficulty:Medium
Example:
Input:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
方法1: 优先队列
- Time complexity : O ( n l o g ( n − k ) ) O\left ( nlog(n-k) \right ) O(nlog(n−k))
- Space complexity :
O
(
n
)
O\left ( n\right )
O(n)
思路:
首先HsahMap存储频率,再利用priority_queue数据结构将pair<frequent, num>存储起来,维护一个n-k的heap,priority_queue的底层是用heap实现的。
//默认是大顶堆
priority_queue<int> a;
//等同于 priority_queue<int, vector<int>, less<int> > a;
//小顶堆,这里一定要有空格,不然成了右移运算符↓
priority_queue<int, vector<int>, greater<int> > c;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
unordered_map<int, int> map;
for (auto num : nums)
map[num]++;
priority_queue<pair<int, int>> pq;
for (auto ite = map.begin(); ite != map.end(); ite++) {
pq.push(make_pair(ite->second, ite->first));
if (pq.size() > map.size() - k) {
res.push_back(pq.top().second);
pq.pop();
}
}
return res;
}
};
方法2: 桶排序
- Time complexity : O ( n ) O\left ( n \right ) O(n)
- Space complexity :
O
(
n
)
O\left ( n\right )
O(n)
思路:
首先HsahMap存储频率,再将map中的value作为index,key作为value转成二维数组,从未到头遍历,直至找到k个。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
unordered_map<int, int> map;
for (auto num : nums)
map[num]++;
vector<vector<int>> buckets(nums.size()+1);
for (auto m : map)
buckets[m.second].push_back(m.first);
for (int i = buckets.size()-1; i >= 0; i--){
for (auto j : buckets[i]){
res.push_back(j);
if(res.size() == k)
return res;
}
}
return res;
}
};