题解 | #最小的K个数#
最小的K个数
http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
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;
}
};