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;
}
};
相關文章
- Leetcode 347. Top K Frequent ElementsLeetCode
- 347. Top K Frequent Elements - Bucket Sorting
- *692. Top K Frequent Words
- 347. 前 K 個高頻元素
- Leetcode——347. 前K個高頻元素LeetCode
- 508-Most Frequent Subtree Sum
- 【Lintcode】1484. The Most Frequent Word
- 如何解決TOP-K問題
- Blocking ElementsBloC
- 推薦系統 TOP K 評價指標指標
- 經典的 Top K 問題,你真的懂了麼?
- SAP Fiori Elements 概述
- k8s kubectl top pod報錯error Metrics API not availableK8SErrorAPIAI
- 程式碼隨想錄 第13天 | ● 239. 滑動視窗最大值 ● 347.前 K 個高頻元素 ● 總結
- SAP Fiori Elements 公開課第二單元學習筆記:Fiori Elements 架構筆記架構
- 【譯】Angular Elements 及其運作原理Angular
- chrome devtools使用詳解——Elements篇Chromedev
- The elements of programming style,好程式的要素
- Adobe推出Premiere和Photoshop Elements 2021REM
- Web Components系列(三) —— 建立 Custom ElementsWeb
- Leetcode 203. Remove Linked List ElementsLeetCodeREM
- LeetCode | 203. Remove Linked List ElementsLeetCodeREM
- Day10(棧與佇列) | 150. 逆波蘭表示式求值 239. 滑動視窗最大值 347.前 K 個高頻元素佇列
- Elements皮膚顯示HTML註釋HTML
- Web Components 系列(二)—— 關於 Custom ElementsWeb
- How to fix elements to the bottom of the container in css? (four ways)AICSS
- Premiere Elements(Pr2023精簡版)REM
- 【Flutter 專題】101 何為 Flutter Elements ?Flutter
- Karabiner Elements for Mac鍵盤改鍵工具Mac
- 【Leetcode】453. Minimum Moves to Equal Array ElementsLeetCode
- LeetCode 1305 All Elements in Two Binary Search TreesLeetCode
- 程式碼隨想錄刷題day 11 | **150. 逆波蘭表示式求值** **239. 滑動視窗最大值** **347.前 K 個高頻元素**
- [譯] Flutter,什麼是 Widgets、RenderObjects 和 Elements?FlutterObject
- Flutter - 手寫體widgets之wired_elementsFlutter
- SAP Fiori Elements controller extension 的載入原理Controller
- Frequent Pattern 資料探勘關聯規則演算法(Aprior演算法) FT-Tree演算法
- top 命令
- SAP Fiori Elements裡Drop down list的實現原理
- ironSource旗下Luna Labs推出IEC製作工具Luna Elements