美文网首页
最小的k个数

最小的k个数

作者: 哦漏昵称已被占用 | 来源:发表于2017-10-12 15:00 被阅读0次

题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

思路
快速排序

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        int len=input.size();
        if(len==0 || k>len ||k<=0) 
            return vector<int>();
        if(len==k)
            return input;
        
        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;
    }
    
    int partition(vector<int> &nums, int begin, int end){
        int low=begin, high=end;
        int pivot=nums[begin];
        while(low<high){
            while(low<high && nums[high]>=pivot)
                high--;
            if(low<high)
                nums[low++]=nums[high];
            while(low<high && nums[low]<=pivot)
                low++;
            if(low<high)
                nums[high--]=nums[low];
        }
        nums[low]=pivot;
        return low;
    }
};

相关文章

  • 算法-数组(三)

    最小的k个数 求子数组的最大和 把数组排成最小的数字 1.最小的k个数 问题描述:输入n个数字,找到数组中最小的k...

  • 最小的k个数

    问题描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是...

  • 最小的k个数

    输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3...

  • 最小的K个数

    题目描述输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1...

  • 最小的k个数

    参考: [1] https://www.nowcoder.com/questionTerminal/6a296eb...

  • 最小的K个数

    输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。

  • 最小的K个数

    题目描述 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是...

  • 最小的k个数

    问题:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,...

  • 最小的k个数

    题目描述输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1...

  • 最小的K个数

    import java.util.Scanner; public class GetLestNumbers { }

网友评论

      本文标题:最小的k个数

      本文链接:https://www.haomeiwen.com/subject/nffoyxtx.html