题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路
快速排序
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int len=input.size();
if(len==0 || k>len ||k<=0)
return vector<int>();
if(len==k)
return input;
int start=0,end=len-1;
int index=partition(input,start,end);
while(index!=(k-1)){
if(index>k-1){
end=index-1;
index=partition(input,start,end);
}else{
start=index+1;
index=partition(input,start,end);
}
}
vector<int> res(input.begin(),input.begin()+k);
return res;
}
int partition(vector<int> &nums, int begin, int end){
int low=begin, high=end;
int pivot=nums[begin];
while(low<high){
while(low<high && nums[high]>=pivot)
high--;
if(low<high)
nums[low++]=nums[high];
while(low<high && nums[low]<=pivot)
low++;
if(low<high)
nums[high--]=nums[low];
}
nums[low]=pivot;
return low;
}
};