iven 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) {
map<int,int> m;
priority_queue<pair<int,int> > q;
vector<int> v;
for (int i = 0; i < nums.size(); ++i) {
m[nums[i]]++;
}
for (auto p: m)
q.push({p.second,p.first});
for (int i = 0; i < k; i++) {
v.push_back(q.top().second);
q.pop();
}
return v;
}
};