题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路一:第一想法是快速排序。(排序的几种方式应当十分熟练)排序后输出相应的需要的数字。c++代码如下:
class Solution {
void quickSort(vector<int>& input,int start,int end){
if(start >= end) return;
int prestart=start;
int preend=end;
int pivotkey=input[start];
while(start < end)
{
while( start < end && input[start] <= pivotkey) start++;
while( start < end && input[end] >= pivotkey) end--;
int temp=input[start];
input[start]=input[end];
input[end]=temp;
}
if(input[start] > pivotkey) start=start-1;
input[prestart]=input[start];
input[start]=pivotkey;
if(start > prestart) quickSort(input,prestart,start-1);
if(start < end ) quickSort(input,start+1,end);
}
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
//快速排序
int length=input.size();
if(k > length) return {};
quickSort(input,0,length-1);
vector<int> res;
for(int i=0;i<k;i++)
{
res.push_back(input[i]);
}
return res;
}
};