class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
int[] vec = new int[k];
if (k == 0) { // 排除 0 的情况
return vec;
}
Queue<Integer> maxheap = new PriorityQueue<>(k, (i1, i2) -> Integer.compare(i2, i1));
for(int i = 0 ;i<arr.length;i++){
if(maxheap.size()<k){
maxheap.offer(arr[i]);
}else{
Integer top = maxheap.peek();
if(top!=null){
if(arr[i]<top){
maxheap.poll();
maxheap.offer(arr[i]);
}
}
}
}
int[] array = new int [k];
for(int i =0 ;i<k;i++){
array[i] = maxheap.poll();
}
return array;
}
}
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4
最新推荐文章于 2022-04-04 10:24:40 发布