LeetCode 347:最高频的 K 个元素
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 347:最高频的 K 个元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
很重點的一道題,是劍指Offer,LeetCode里面常見的另一道題:返回數組里最小/大的K個元素進階版。
同時也是海量數據處理課里講過的一道基礎題,后序還有各種進階的在線解法。
自己有思路但因為語法不夠熟練,參考了討論區的解法寫的程序:涉及到了很多C++基礎知識,值得好好復習。
C++ STL 優先隊列的應用
缺點:最后是倒序輸出的。
class Solution { public://using value_t = pair<int, int>; //不要忘記等號typedef pair<int, int> value_t;// 因為堆中元素不是標準的數據類型 && 要用最小堆,需要定義struct cmp {bool operator() (const value_t& a, const value_t& b) {return a.second > b.second;}}; //結構體定義的分號不可少!!!vector<int> topKFrequent(vector<int>& nums, int k) {int n = nums.size();vector<int> ret;if(nums.empty()) return ret; //1-將數組轉換成哈希表unordered_map<int, int> dict;for (auto num : nums) {dict[num] ++;}//2-將哈希表存入最小堆中,將多余的元素彈出,留下的最后k項就是最高頻的k項//using value_t pair<int, int>;priority_queue<value_t, vector<value_t>, cmp> pq;for (auto a : dict) {pq.push(a);if(pq.size() > k) {pq.pop();}}//3-將堆中元素保存到數組中返回,但這樣是倒序輸出的while(!pq.empty()) {ret.push_back(pq.top().first);pq.pop();}return ret;} };?最大堆:最后是正序輸出的,與最小堆的性能對比見末尾。
class Solution { public://using value_t = pair<int, int>; //不要忘記等號typedef pair<int, int> value_t;// 因為堆中元素不是標準的數據類型 && 要用最小堆,需要定義struct cmp {bool operator() (const value_t& a, const value_t& b) {return a.second < b.second;}}; //結構體定義的分號不可少!!!vector<int> topKFrequent(vector<int>& nums, int k) {int n = nums.size();vector<int> ret;if(nums.empty()) return ret; //1-將數組轉換成哈希表unordered_map<int, int> dict;for (auto num : nums) {dict[num] ++;}//2-將哈希表存入最大堆中//using value_t pair<int, int>;priority_queue<value_t, vector<value_t>, cmp> pq;for (auto a : dict) {pq.push(a);}//3-將堆中元素保存到數組中返回,但這樣的倒序輸出的for(int i=0; i<k; i++) {ret.push_back(pq.top().first);pq.pop();}return ret;} };效率對比:
改用最大堆,最后結果是按照頻率逐高到低排序的,但是建堆的時間復雜度O(n),空間也是O(n),取k個元素是O(klogn),
時間O(n) + O(n) + O(klogn),空間也是O(n)。
用最小堆時間復雜度:遍歷建哈希表O(n) + 維護一個大小為k的堆O(nlogk),空間復雜度最壞O(n) + O(k)。
總結
以上是生活随笔為你收集整理的LeetCode 347:最高频的 K 个元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [ubuntu]用SSH实现ubuntu
- 下一篇: cocos2dx-2.2.6版本下载地址