国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

347. Top K Frequent Elements

2019-11-14 09:33:53
字體:
供稿:網(wǎng)友

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,時(shí)間復(fù)雜度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; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 红安县| 中牟县| 霞浦县| 兰州市| 阳山县| 隆林| 井冈山市| 贵德县| 富锦市| 乌兰浩特市| 长治市| 天祝| 搜索| 札达县| 翼城县| 樟树市| 普定县| 平乐县| 开江县| 正镶白旗| 巴林右旗| 青铜峡市| 阿巴嘎旗| 通河县| 榆社县| 郁南县| 当涂县| 伊川县| 壤塘县| 玛多县| 客服| 温宿县| 开阳县| 南阳市| 依安县| 余江县| 大邑县| 上饶县| 衡东县| 商南县| 宜宾市|