输入n个整数,找出其中最小的K个数

题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
* 思路一:快排
* 思路二:堆排解决/时间复杂度O(nlogk) 适合海量数据

public class FindKthLeastNum {
    //使用快速排序Partition函数
    public int partition(int[] arr,int left,int right){
        int index = arr[left];//第一个做哨兵
        if(left > right){
            return -1;
        }

        while (left < right){
            while (left < right && arr[right] >= index){//右侧>哨兵
                right--;//右指针向前移动
            }
            arr[left] = arr[right];//出现右侧<哨兵
            while (left < right && arr[left] < index){//左侧<哨兵
                left++;//左指针向后移动
            }
            arr[right] = arr[left];//出现左侧>哨兵
        }
        arr[left] = index;
        return left;//返回哨兵位置
    }

    public int[] GetLeastNumbers_Solution(int [] input, int k) {
        if(input.length == 0 || k <= 0)
            return null;
        int[] output = new int[k];
        int start = 0;
        int end = input.length-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);
            }

        }
        for (int i =0;i < k;i++){
            output[i] = input[i];
        }
        return output;
    }

    public static void main(String[] args) {
        int[] arr = {4,5,1,6,2,7,3,8};
        FindKthLeastNum test = new FindKthLeastNum();
        int[] output = test.GetLeastNumbers_Solution(arr,4);
        for (int i = 0;i",");
        }
    }
}

你可能感兴趣的:(校招算法题)