输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
解题思路:
借助快排partition函数 (这次partiton函数没有写错,嘻嘻)
错误点:
- 没有写这一行,如果不写当nk时会溢出,if(nk) return arr;
- 这个地方竟然忘记写pos了,pos = partition(arr,beg,end);
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
int n = arr.size();
if(n==0) return vector<int>{};
if(n==k) return arr;
int pos = 0;
int beg=0,end=n-1;
vector<int> res;
pos = partition(arr,beg,end);
while(pos!=k){
if(pos > k){
end = pos-1;
pos = partition(arr,beg,end);
}else if(pos<k){
beg = pos+1;
pos = partition(arr,beg,end);
}
}
for(int i=0;i<k;i++){
res.push_back(arr[i]);
}
return res;
}
int partition(vector<int>& arr,int beg,int end){
int pivot = arr[beg];
int i=beg,j=end;
while(i<j){
while(i<j&&pivot<=arr[j]){
j--;
}
while(i<j&&pivot>=arr[i]){
i++;
}
if(i<j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
arr[beg] = arr[i];
arr[i] = pivot;
return i;
}
};