剑指offer - 最小的K个数

来源:互联网 发布:为何手机淘宝打不开 编辑:程序博客网 时间:2024/06/08 05:51
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;    }};
0 0