#最小的k个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nwpubear/article/details/82467807

最小的k个数字

快排分治的方法进行计算
1. 快排一次得到中间枢纽位置,比较在k-1后面还是前面
2. 若是index>k-1,那么就对[left,index-1]在进行快排
3. 若是index

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> ret;
        int len=input.size();
        if(k>len || len==0 || k<=0  )
            return ret;
        int left=0;
        int right=len-1;
        int index=partition(input,left,right);
        while(index!=k-1){
            if(index>k-1){
                right=index-1;
                index=partition(input,left,right);
            }
            else{
                left=index+1;
                index=partition(input,left,right);
            }
        }

        ret.insert(ret.end(),input.begin(),input.begin()+index+1);
        return ret;
    }
    int partition(vector<int>& input,int left,int right){
        if(left>=right)
            return left;
        int flag=input[left];
        int l=left;
        while(left<right){
            while(right>left && input[right]>=flag)
                right--;
            while(left<right && input[left]<=flag)
                left++;
            swap(input[left],input[right]);
        }
        swap(input[l],input[left]);
        return left;
    }
};

猜你喜欢

转载自blog.csdn.net/nwpubear/article/details/82467807