class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{
vector<int> res;
if(input.empty()||input.size()<k||k<=0)
return res;
int low=0,high=input.size()-1,mid=-1;
while(mid!=(k-1))
{
if(mid>(k-1))
high=mid-1;
else
low=mid+1;
mid=Partition(input,low,high);
}
for(int i=0;i<=mid;i++)
res.push_back(input[i]);
return res;
}
int Partition(vector<int> &n,int low,int high)
{
int key=n[low];
while(low<high)
{
while(low<high&&key<=n[high])
high--;
n[low]=n[high];
while(low<high&&key>=n[low])
low++;
n[high]=n[low];
}
n[low]=key;
return low;
}
};
剑指offer - 最小的K个数
最新推荐文章于 2024-04-23 21:26:48 发布