题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路:1,快排思想,一次partition找到第low小位置,多次partition直到low==k-1为止;2,维护一个大顶推,依次遍历,更新堆,时间复杂度为O(nlogk)。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int len = input.size();
vector<int> result;
if(len==0||k<=0||k>len)
return result;
int x=GetLeastNumbers_SolutionCore(input, k,0,len-1);
while(x!=k-1)
{
if(x>k-1)
x=GetLeastNumbers_SolutionCore(input, k, 0, x-1);
else
x=GetLeastNumbers_SolutionCore(input, k, x+1, len-1);
}
for(int i=0;i<k;i++)
result.push_back(input[i]);
return result;
}
int GetLeastNumbers_SolutionCore(vector<int> &input, int k,int low,int high)
{
int temp=input[low];
while(low<high)
{
while(low<high&&input[high]>=temp)
high--;
input[low]=input[high];
while(low<high&&input[low]<=temp)
low++;
input[high]=input[low];
}
input[low]=temp;
return low;
}
};