美文网首页
最小的K个数

最小的K个数

作者: 柳仁儿 | 来源:发表于2017-09-18 11:15 被阅读0次

    import java.util.Scanner;

    public class GetLestNumbers {

    // 判断数组是否为空
    public static boolean checkInvalidArray(int[] numbers) {
        if (numbers == null || numbers.length == 0)
            return true;
        return false;
    }
    
    // 基于快速排序算法的partition函数
    public static int partition(int[] numbers, int left, int right) {
        int result = numbers[left];
        if (left > right) {
            return -1;
        }
        while (left < right) {
            while (left < right && numbers[right] >= result) {
                right--;
            }
            numbers[left] = numbers[right];
            while (left < right && numbers[left] < result) {
                left++;
            }
            numbers[right] = numbers[left];
        }
        numbers[left] = result;
        return left;
    }
    
    // 基于Partition函数的O(n)算法
    public static int[] getLestNumbersK(int[] numbers, int k) {
        int[] results = new int[k];
        if (checkInvalidArray(numbers))
            return null;
        int length = numbers.length;
        int start = 0;
        int end = length - 1;
        int index = partition(numbers, start, end);
        while (index != k - 1) {
            if (index > k - 1) {
                end = index - 1;
                index = partition(numbers, start, end);
            } else {
                start = index + 1;
                index = partition(numbers, start, end);
            }
    
        }
        for (int i = 0; i < k; i++) {
            results[i] = numbers[i];
        }
        return results;
    }
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String string = input.nextLine();
        int k = input.nextInt();
        String[] inputnum = string.split(" ");
        int[] numbers = new int[inputnum.length];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = Integer.parseInt(inputnum[i]);
        }       
        for (int number : getLestNumbersK(numbers, k)) {
            System.out.print(number + " ");
        }
    }
    

    }

    相关文章

      网友评论

          本文标题:最小的K个数

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