其他分享
首页 > 其他分享> > 输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4

输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4

作者:互联网

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,数字,int,maxheap,最小,new,array,poll,输入
来源: https://blog.csdn.net/zylscxy/article/details/113995784