347. Top K Frequent Elements

題目:

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;
    }
};

知識點:

  1. C++自己帶的heap,在庫<queue>裏,Doc
  2. 複習了unordered_map<type, type>,用iterator時候,索引爲i.first,數值爲i.second
  3. 散列表複雜度nn,二叉堆插入元素複雜度是log(k)log(k)kk爲堆的高度。插入了nn個元素,所以總的複雜度是nlog(k)nlog(k)
  4. 堆的高度只需要kk,如果堆高於kk了,就扔掉最後的元素。
  5. c++的iterator:for(auto i:nums)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章