LeetCode 最小的k个数 [简单]
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:
输入:arr = [0,1,2,1], k = 1
输出:[0]
限制:
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
题目分析
解法1
使用大根堆实现
解法2
先把数组排序,然后取出前k个元素即可
代码实现
public class GetLeastNumbers {
public static void main(String[] args) {
int[] arr = {3, 2, 1};
int k = 2;
int[] leastNumbers = getLeastNumbers(arr, k);
System.out.println(Arrays.toString(leastNumbers));
}
public static int[] getLeastNumbers1(int[] arr, int k) {
if (k == 0) {
return new int[0];
}
Queue<Integer> heap = new PriorityQueue<>(k, (i1, i2) -> Integer.compare(i2, i1));
for (int ele : arr) {
if (heap.isEmpty() || heap.size() < k || ele < heap.peek()) {
heap.offer(ele);
}
if (heap.size() > k) {
heap.poll();
}
}
int[] res = new int[heap.size()];
int j = 0;
for (Integer ele : heap) {
res[j++] = ele;
}
return res;
}
public static int[] getLeastNumbers(int[] arr, int k) {
if (arr == null || arr.length == 0 || k == 0 || k > arr.length) {
return new int[]{};
}
if (k == arr.length) {
return arr;
}
int[] res = new int[k];
Arrays.sort(arr);
for (int i = 0; i < k; i++) {
res[i] = arr[i];
}
return res;
}
}