老师,第347题按照你的提示,我提交了如下代码,但好像代码没有变得更简洁,请问如何更改进呢?
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
//(元素,频率)
unordered_map<int,int> freq;
unordered_map<int,int>::iterator iter;
for(int num:nums)
freq[num]++;
int n = freq.size();
//(频率,元素)
priority_queue<pair<int,int>> pq;
for(iter=freq.begin();iter!=freq.end();iter++){
if(pq.size() == n-k) {
if(n-k!=0 && iter->second < pq.top().first) {
pq.pop();
pq.push(make_pair(iter->second,iter->first));
}
}
else
pq.push(make_pair(iter->second,iter->first));
}
while(!pq.empty()) {
freq.erase(pq.top().second);
pq.pop();
}
for (auto k:freq)
res.push_back(k.first);
return res;
}
};