leetcode347 前 K 個高頻元素

題目描述:leetcode347前 K 個高頻元素

思路:將元素加入hashmap建立<數字,頻率>的映射,然後藉助priority_queue<頻率,數字>實現最大堆,取最大堆的k個元素,時間複雜度O(k logN)

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        priority_queue<pair<int, int>> q;
        vector<int> res;
        for (auto a : nums) ++m[a];
        for (auto it : m) q.push({it.second, it.first});
        for (int i = 0; i < k; ++i) {
            res.push_back(q.top().second); q.pop();
        }
        return res;
    }
};

優化思路:

1,維持堆的大小爲k

2,haspmap+桶排序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章