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

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

347. Top K Frequent Elements

2019-11-14 09:02:25
字體:
供稿:網(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,時間復(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ā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 安阳市| 辽宁省| 广平县| 吉水县| 桐庐县| 浮山县| 余江县| 理塘县| 德清县| 班玛县| 内黄县| 石台县| 慈利县| 辽阳市| 房山区| 中阳县| 临汾市| 繁昌县| 绥江县| 桃园县| 延边| 五大连池市| 厦门市| 保山市| 盖州市| 铜梁县| 迁安市| 调兵山市| 温宿县| 夏河县| 宿迁市| 凤阳县| 响水县| 陆良县| 德昌县| 莆田市| 汉源县| 碌曲县| 和平区| 昔阳县| 屯昌县|