牛客网刷题(JAVA) 15:最小的k个数

难度系数 ⭐

时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

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

思路 利用归并排序排好序后,依次取出k个数即可。
 

package nowcoder;

import java.util.ArrayList;
import java.util.Arrays;

public class No15 {
    public static ArrayList GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList res = new ArrayList<>();

        if (input == null || input.length < k || k == 0) return res;

        sort(input, 0, input.length - 1);

        for (int i = 0; i < k; i++)
            res.add(input[i]);

        return res;
    }

    public static void sort(int[] arr, int L, int R){
        if (L == R) return;

        int mid = L + (R - L) / 2;
        sort(arr, L, mid);
        sort(arr, mid + 1, R);
        merge(arr, L, R, mid);
    }

    public static void merge(int[] arr, int L, int R, int mid){
        int p1 = L;
        int p2 = mid + 1;

        int[] flag = new int[R - L + 1];
        int i = 0;

        while (p1 <= mid && p2 <= R) flag[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        while (p1 <= mid) flag[i++] = arr[p1++];
        while (p2 <= R) flag[i++] = arr[p2++];

        for (int j = 0; j < flag.length; j++)
            arr[L + j] = flag[j];
    }

    public static void main(String[] args){
        int[] arr = {1, 32, 53, 3, 31, 2, 1, 3};
        int k = 40;
        System.out.println(GetLeastNumbers_Solution(arr, k));
    }
}

 

你可能感兴趣的:(牛客网题库)