class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{
vector<int> result;
int len = input.size();
if (len == 0 || k < 0 || k > len) return result;
int start = 0, end = len - 1;
int index = partition(input,start, end);
while (index != (k-1))
{
if (index > k - 1)
{
end = index - 1;
index = partition(input, start, end);
}
else
{
start = index + 1;
index = partition(input, start, end);
}
}
vector<int> res(input.begin(), input.begin() + k);
return res;
}
private:
int partition(vector<int>& input, int start, int end)
{
int low = start;
int high = end;
int pivot = input[low];
while ((low < high))
{
while (low < high && pivot <= input[high]) --high;
input[low] = input[high];
while (low < high && pivot >= input[low]) ++low;
input[high] = input[low];
}
input[low] = pivot;
return low;
}
};
最小的K个数--(快排法)
最新推荐文章于 2023-04-07 09:42:25 发布