题目:
输入n个整数,找出其中最小的k个数。
思路:
最简单的思路,还是把数组整体排序,排序之后位于前k个的数就是前k个数。但这样的思路时间复杂度太高了,所以我们需要寻求效率更高的算法。
基于上一题的想法我们一样的可以进行快排,然后随便挑一个数字,看这个挑的数字下标位置和下标位置k的位置关系,从而找到这个下标k位置的数,然后输出左边所有的数字。
int Partition(int* a, int low, int high){
int pivot = a[low];
while(low<high){
while(low<high && a[high]>=pivot) high--;
a[low] = a[high];
while(low<high && a[low]<=pivot) low++;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
int* getLeastNumbers(int* arr, int arrSize, int k, int* returnSize){
int low = 0;
int high = arrSize-1;
int pos = Partition(arr,low,high);
if(k<=0){
*returnSize = 0;
return NULL;
}
while(pos!=k-1){
if(pos>k-1){
high = pos-1;
pos = Partition(arr,low,high);
}
else{
low = pos + 1;
pos = Partition(arr,low,high);
}
}
*returnSize = k;
int* result = (int*)malloc(sizeof(int)*k);
for(int i = 0;i<k;i++)
result[i] = arr[i];
return result;
}