最大堆解法,代码不多
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
priority_queue<int> big_heap;
vector<int> res = {};
priority_queue<int> big_heap;
vector<int> res = {};
if(k == 0){
return res;
}
for(int a : input){
if(big_heap.size() < k){
big_heap.push(a);
}else if(big_heap.size() == k){
if(big_heap.top() > a){
big_heap.pop();
big_heap.push(a);
}
}
}
while(!big_heap.empty()){
res.push_back(big_heap.top());
big_heap.pop();
}
return res;
}
return res;
}
for(int a : input){
if(big_heap.size() < k){
big_heap.push(a);
}else if(big_heap.size() == k){
if(big_heap.top() > a){
big_heap.pop();
big_heap.push(a);
}
}
}
while(!big_heap.empty()){
res.push_back(big_heap.top());
big_heap.pop();
}
return res;
}