題目:
Given a non-empty array of integers, return the k most frequent elements.
例子:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Input: nums = [1], k = 1
Output: [1]
注意:
- 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.
思路:
統計出現次數就可以想到哈希表,但是這裏不要忽略了排序的問題,這個就是個哈希+排序。這裏其實都是整數,所以可以用線性排序,比如桶排序。
代碼
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for(auto num:nums){
counts[num]++;
}
priority_queue<int, vector<int>, greater<int>> heap;
for(auto count:counts){
heap.push(count.second);
if(heap.size() > k){
heap.pop();
}
}
vector<int> ret;
for(auto i:counts){
if(i.second >= heap.top()){
ret.push_back(i.first);
}
}
return ret;
}
};
知識點:
- C++自己帶的heap,在庫
<queue>
裏,Doc - 複習了
unordered_map<type, type>
,用iterator時候,索引爲i.first
,數值爲i.second
。 - 散列表複雜度,二叉堆插入元素複雜度是,爲堆的高度。插入了個元素,所以總的複雜度是。
- 堆的高度只需要,如果堆高於了,就扔掉最後的元素。
- c++的iterator:
for(auto i:nums)