[347] Top K Frequent Elements

来源:互联网 发布:手游龙之刃升阶数据 编辑:程序博客网 时间:2024/06/18 14:58

【题目描述】

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.

【解题思路】

先用哈希表扫描一遍,然后用最大堆来求出最大的k个值

【代码】

class Solution {public:    vector<int> topKFrequent(vector<int>& nums, int k) {        int sz=nums.size();        vector<int> vec;        if(sz==0) return vec;        map<int,int> m;        priority_queue<pair<int, int> >pq;        for(int i=0;i<sz;i++){            m[nums[i]]++;        }        map<int, int>::iterator  iter;        for(iter=m.begin();iter!=m.end();iter++){            pq.push(make_pair(iter->second,iter->first));        }       while(k--){           vec.push_back(pq.top().second);           pq.pop();       }       return vec;    }};



0 0
原创粉丝点击