无序数组中的最小k个数

题目描述

对于一个无序数组,数组中元素为互不相同的整数,请返回其中最小的k个数,顺序与原数组中元素顺序一致。

给定一个整数数组A及它的大小n,同时给定k,请返回其中最小的k个数。

测试样例

[1, 2, 3, 4], 4, 2

返回:[1, 2]

解析

import java.util.*;

public class KthNumbers {
    public int[] findKthNumbers(int[] A, int n, int k) {
        // write code here
        if (n < k) return null;
        if (k == n) return A;
        int[] b = Arrays.copyOf(A, n);
        Arrays.sort(b);
        int target = b[k - 1];
        int[] arr = new int[k];
        int p = 0;
        for (int i = 0; i < n; i++) {
            if (A[i] <= target) {
                arr[p++] = A[i];
            }
        }
        return arr;
    }
}

猜你喜欢

转载自blog.csdn.net/lutte_/article/details/80500343