AcWing 53. 最小的k个数
原题链接
简单
作者:
未名湖畔的梦
,
2021-05-05 21:28:51
,
所有人可见
,
阅读 210
#include <algorithm>
// C++ 不用 sort 感觉亏了一个亿
class Solution {
public:
vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
if(!input.size()) return input;
sort(input.begin(), input.begin() + input.size());
vector<int>res;
for(int i = 0; i < k; i++)res.push_back(input[i]);
return res;
}
};
//堆排序
class Solution {
public:
vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
vector<int> ans;
priority_queue<int> heap;
for(auto x : input){
heap.push(x);
if(heap.size() > k) heap.pop();
}
while(heap.size()){
ans.push_back(heap.top());
heap.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};