好像没什么好讲的,priority_queue的迭代器比较奇怪..
typedef pair<int, int> P;
struct cmp{
bool operator() (P a, P b){
return a.first > b.first;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
priority_queue<P, vector<P>, cmp> a;
vector<int> ans;
for(auto it = nums.begin(); it != nums.end(); ){
int count = 1;
while(*it == *(++it))
count++;
if(k > a.size())
a.push(make_pair(count, *(it-1)));
else if(count > a.top().first)
a.pop(),a.push(make_pair(count, *(it-1)));
}
while(a.size())
ans.push_back(a.top().second), a.pop();
return ans;
}
};