Practice19:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
S1
解题之一
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(input.empty()||k==input.size())return input;
if(k==0 || k>input.size())return {};
sort(input.begin(),input.end());
vector<int> res(input.begin(),input.begin()+k);
return res;
}
};
S2
牛客解题之一:
大顶堆优先队列
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
if(k==0 || k>input.size())return res;
priority_queue<int,vector<int>> pq;
for(const int val:input){
if(pq.size()<k){
pq.push(val);
}
else{
if(val<pq.top()){
pq.pop();
pq.push(val);
}
}
}
while(!pq.empty()){
res.push_back(pq.top());
pq.pop();
}
return res;
}
};