topK问题,用一个大小为K的堆实现。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> result{};
if(k==0) return result;
priority_queue<int,vector<int>,less<int>> max_heap{};
for(int i=0;i<k;i++){
max_heap.push(input[i]);
}
for(int i=k;i<input.size();++i){
if(input[i]<max_heap.top()){
max_heap.pop();
max_heap.push(input[i]);
}
}
while(!max_heap.empty()){
result.push_back(max_heap.top());
max_heap.pop();
}
return result;
}
};