阿里一面直挂题
2018-03-31 本文已影响8人
leon4ever
给定一个巨大的无序数组,输出数组中出现次数最多的K个数。
思路很简单,TopN问题,真的是足够简单了,然而我还是写了半天,还特么没写对
class Solution{
//默认是最大堆,重载一下操作符(反过来的),就能实现最小堆
struct cmp{
bool operator()(const pair<int ,int>& a, const pair<int, int>& b){
return a.second > b.second;
}
};
public:
vector<int> findtopN(vector<int>& num, int N){
unordered_map<int, int> hmap;
for(int value : num)
hmap[value]++;
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> heap;
auto iter = hmap.begin();
for(int i = 0; i < N ; i++, iter++){
heap.push(*iter);
}
for( ; iter!=hmap.end(); iter++){
if(iter->second > heap.top().second){
heap.pop();
heap.push(*iter);
}
}
vector<int> result;
while(!heap.empty()){
result.push_back(heap.top().first);
heap.pop();
}
sort(result.begin(), result.end());
return result;
}
};
···