面试题 17.14. 最小K个数
2021.9.3
class Solution {
public:
vector<int> smallestK(vector<int>& nums, int k)
{
qsort(nums,k,0,nums.size()-1);
return res;
}
private:
vector<int> res;
void qsort(vector<int>& vec, int k,int left,int right)
{
if(left > right) return;
int i = left;
int j = right;
//vec[left] is base
while(i<j)
{
while(i<j && vec[j] >= vec[left]) --j;
while(i<j && vec[i] <= vec[left]) ++i;
swap(vec[i],vec[j]);
}
swap(vec[i],vec[left]);
if(i == k) res.assign(vec.begin(),vec.begin()+k);
else if(i > k) qsort(vec,k,left,i-1);
else qsort(vec,k,i+1,right);
}
};