剑指 Offer 40. 最小的k个数

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
            if(k==0||arr.length<=0){
                return new int[0];
            }

            //默认是最小根堆,实现大根堆需要重写比较器
            Queue<Integer> pq = new PriorityQueue<>((v1,v2)->v2 - v1);

            for(int num:arr){
                if(pq.size()<k){
                    pq.offer(num);
                }else if(num< pq.peek()){
                    pq.poll();
                    pq.offer(num);
                }
            }
            //返回堆中元素
            int[] res = new int[pq.size()];
            int idx = 0;
            for(int num:pq){
                res[idx++] = num;
            }
            return res;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/14143326.html