给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1] 。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
unordered_map<int, int> M;
priority_queue<pair<int, int>> Q;
for(int i =0 ; i < nums.size(); i++)
M[nums[i]]++;
for(auto it: M)
Q.push({it.second, it.first});
for(int i = 0; i < k; i++)
{
int top = Q.top().second;
Q.pop();
res.push_back(top);
}
return res;
}
};