My solution:
1. Use sort () to sort the vector, insert the first k elements into vector <int> res
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
vector<int> res;
if(arr.empty()) return res;
sort(arr.begin(),arr.end());
for(int i=0;i<k;i++)
res.push_back(arr[i]);
return res;
}
};
2. Quick Sort
Compare the number of elements on the left of pivot with K in quick sort
It should be noted that, but k> this number is needed, and the right side of the array needs to be sorted, the value of k needs to be changed (stuck here for a long time)
quicksort(nums,i+1,r,k-i+l-1)
class Solution {
public:
void quicksort(vector<int>&nums,int l,int r,int k){
if(l>=r) return;
int i=l,j=r;
int pivot=nums[l];
while(i<j){
while(nums[j]>=pivot&&i<j) j--;
if(i<j) nums[i++]=nums[j];
while(nums[i]<=pivot&&i<j) i++;
if(i<j) nums[j--]=nums[i];
}
nums[i]=pivot;
if(i-l+1==k) return;
if(k>i-l+1) quicksort(nums,i+1,r,k-i+l-1);
else if(k<i-l+1) quicksort(nums,l,i-1,k);
}
vector<int> getLeastNumbers(vector<int>& arr, int k) {
vector<int> res;
if(arr.empty()) return res;
quicksort(arr,0,arr.size()-1,k);
for(int i=0;i<k;i++)
res.push_back(arr[i]);
return res;
}
};