LeetCode 面试题 17.14 最小K个数

设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。

示例:

输入: arr = [1,3,5,7,2,4,6,8], k = 4
输出: [1,2,3,4]

优先级队列

public static int[] smallestK(int[] arr, int k) {
    if (arr == null || k == 0) return new int[]{};
    if (arr.length <= k) return arr;

    Queue<Integer> integerPriorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
    for (int i = 0; i < k; i++) {
        integerPriorityQueue.offer(arr[i]);
    }
    for (int i = k; i < arr.length; i++) {
        if (integerPriorityQueue.peek() > arr[i]) {
            integerPriorityQueue.poll();
            integerPriorityQueue.offer(arr[i]);
        }
    }

    int[] ans = new int[k];
    for (int i = 0; i < k; i++) {
        ans[i] = integerPriorityQueue.poll();
    }
    return ans;
}

排序

public static int[] smallestK(int[] arr, int k) {
    if (arr == null || k == 0) return new int[]{};
    if (arr.length <= k) return arr;
    quickSort(arr, 0, arr.length - 1);
    int[] ans = new int[k];
    for (int i = 0; i < k; i++) {
        ans[i] = arr[i];
    }
    return ans;
}
posted @ 2021-09-03 14:34  枫叶艾辰  阅读(34)  评论(0编辑  收藏  举报