347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
- Given [1,1,1,2,2,3] and k = 2, return [1,2].
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.
使用unordered_map和priority_queue,時間複雜度O(n*lg(n-k))。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> ump;
for(auto num : nums)
ump[num]++;
vector<int> res;
priority_queue<pair<int, int>> pq;
for(auto it : ump){
pq.push(make_pair(it.second, it.first)); //pair<first, second>, in priority_queue ths first is frequency, second is number
if(pq.size() > ump.size() - k){
res.push_back(pq.top().second);
pq.pop();
}
}
return res;
}
};
相關文章
- 347. Top K Frequent Elements - Bucket Sorting
- Leetcode 347. Top K Frequent ElementsLeetCode
- LeetCode-Top K Frequent ElementsLeetCode
- *692. Top K Frequent Words
- Leetcode——347. 前K個高頻元素LeetCode
- 如何解決TOP-K問題
- Spark FPGrowth (Frequent Pattern Mining)Spark
- BFPRT 演算法(TOP-K問題)演算法
- 推薦系統 TOP K 評價指標指標
- 經典的 Top K 問題,你真的懂了麼?
- UVA 11235-Frequent values(RMQ)MQ
- 程式碼隨想錄 第13天 | ● 239. 滑動視窗最大值 ● 347.前 K 個高頻元素 ● 總結
- 【Lintcode】1484. The Most Frequent Word
- POJ 3368 Frequent values (UVA 11235)(RMQ)MQ
- SAP Fiori Elements 公開課第二單元學習筆記:Fiori Elements 架構筆記架構
- 【譯】Angular Elements 及其運作原理Angular
- Web Components之Custom ElementsWeb
- Centering HTML elements larger than their parentsHTML
- chrome devtools使用詳解——Elements篇Chromedev
- Elements皮膚顯示HTML註釋HTML
- The elements of programming style,好程式的要素
- Karabiner Elements for Mac鍵盤改鍵工具Mac
- 經典演算法-海量資料處理演算法(top K問題)演算法
- Web Components系列(三) —— 建立 Custom ElementsWeb
- POJ 3368-Frequent values(RMQ+離散化-最頻繁的元素)MQ
- [譯] Flutter,什麼是 Widgets、RenderObjects 和 Elements?FlutterObject
- Flutter - 手寫體widgets之wired_elementsFlutter
- 【Flutter 專題】101 何為 Flutter Elements ?Flutter
- How to fix elements to the bottom of the container in css? (four ways)AICSS
- Web Components 系列(二)—— 關於 Custom ElementsWeb
- Chrome開發者工具中Elements(元素)斷點的用途Chrome斷點
- leetcode刷題--Remove Linked List ElementsLeetCodeREM
- Elements Of A Game Engine - 3D遊戲引擎原理 (轉)GAM3D遊戲引擎
- 經典面試問題: Top K 之 —- 海量資料找出現次數最多或,不重複的。面試
- 經典面試問題: Top K 之 ---- 海量資料找出現次數最多或,不重複的。面試
- SAP Fiori Elements controller extension 的載入原理Controller
- 【Leetcode】453. Minimum Moves to Equal Array ElementsLeetCode
- LeetCode | 203. Remove Linked List ElementsLeetCodeREM