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.

很常見的top-k問題,我一開始的想法就是用哈希表來實(shí)現(xiàn)。
注意priority_queue的使用,排序是first,所以把second放在first。

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> map;
        priority_queue<pair<int, int>> pq;
        vector<int> res;
        int n = nums.size();
        for (int i=0; i<n; i++) {
            map[nums[i]]++;
        }
        for (auto iter=map.begin(); iter!=map.end(); iter++) {
            pq.push(make_pair(iter->second, iter->first));
        }
        for (int i=0; i<k; i++) {
            res.push_back(pq.top().second);
            pq.pop();
        }
        return res;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,775評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,932評(píng)論 0 23
  • 一 月亮到霓虹的距離只值六便士嘛? 這是我戀愛時(shí)的常用口頭禪,我一共對(duì)趙茜說了6次,對(duì)笛安說了14次。 不過我都沒...
    文殊龍膽popkmer閱讀 279評(píng)論 0 0
  • 血靈傳說目錄血靈傳說 (27)
    李一十八閱讀 488評(píng)論 0 0
  • 通往山門的路,在山門兩側(cè)一東一西,兩個(gè)大院,一樣的大鐵門,一樣的兩層小樓,小樓都很舊,連同院墻都是粗糙的水泥...
    純熙2019閱讀 207評(píng)論 0 2