题目描述
算法分析
可以利用划分函数实现,循环此函数直到返回值是 k-1 ,此时 0 - k-1 即为最小的 K 个数
程序代码
class Solution {
public:
int Partition(vector<int> &input, int start, int end)
{
int temp = input[start];
int i = start;
int j = end;
while(i < j)
{
while(i < j && input[j] >= temp) j--;
if(i < j) input[i] = input[j];
while(i < j && input[i] <= temp) i++;
if(i < j) input[j] = input[i];
}
input[i] = temp;
return i;
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{
vector<int> res;
//一定要对特殊情况进行处理
if(input.empty() || k <= 0 || k > input.size())
return res;
int start = 0;
int end = input.size()-1;
int index = Partition(input, start, end);
while(index != k-1)
{
if(index < k-1)
{
start = index + 1;//此处要更新start
index = Partition(input, start, end);
}
else
{
end = index - 1;//次数要更新end,只有更新 end 才会一直变化
index = Partition(input, start, end);
}
}
for(int j = 0; j < k; j++)
res.push_back(input[j]);
return res;
}
};