题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,
代码
class Solution {
public:
//维护一个k大小的最大堆
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> ans;
if (k > 0 && k <= input.size()) {
for (int i = 0; i < k && i < input.size(); ++i) {
ans.push_back(input[i]);
}
make_heap(ans.begin(), ans.end());
for (int i = k; i < input.size(); ++i) {
if (ans[0] > input[i]) {
pop_heap(ans.begin(), ans.end());
ans[k - 1] = input[i];
push_heap(ans.begin(), ans.end());
}
}
sort_heap(ans.begin(), ans.end());
}
return ans;
}
};