力扣面试题40 最小的k个数
class Solution {
public:
void quickSort(vector<int>& arr, int left, int right, int k)
{
if (left >= right || k < left || k > right)
return;
int l = left, r = right, pivot = arr[left];
while (l <= r)
{
while (l <= right && arr[l] <= pivot)l++;
while (left <= r && arr[r] > pivot)r--;
if (l < r)
{
int temp = arr[l];
arr[l++] = arr[r];
arr[r--] = temp;
}
}
if (l > r)
l--;
arr[left] = arr[l];
arr[l] = pivot;
if (k <= l)
{
quickSort(arr, left, l - 1, k);
}
else
{
quickSort(arr, l + 1, right, k);
}
}
vector<int> getLeastNumbers(vector<int>& arr, int k)
{
quickSort(arr, 0, arr.size() - 1, k);
vector<int> v;
v.assign(arr.begin(), arr.begin() + k);
return v;
}
};