題目描述
輸入n個整數(shù),找出其中最小的K個數(shù)。例如輸入4,5,1,6,2,7,3,8這8個數(shù)字,則最小的4個數(shù)字是1,2,3,4,。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
priority_queue<int,vector<int>,less<int>> smallestK; //大頂堆,對頭元素最大
//priority_queue<int,vector<int>,greater<int>> biggestK;//小頂堆,對頭元素最小
int n = input.size();
vector<int> rec;
if(n<=0||k<=0||k>n)
return rec;
for(int i=0;i<n;i++)
{
if(smallestK.size()<k)
smallestK.push(input[i]);
if(smallestK.size()==k)
{
if(input[i]<smallestK.top())
{
smallestK.pop();
smallestK.push(input[i]);
}
}
}
for(int i=0;i<k;i++)
{
rec.push_back(smallestK.top());
smallestK.pop();
}
return rec;
}
};