【13】堆排序 最小K个数

题目

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

收获

优先队列实现
(n1,n2)->n2-n1是大顶堆

代码

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        PriorityQueue<Integer> h = new PriorityQueue<Integer>((n1,n2)->n2-n1);
        for(int i : arr){
            h.add(i);
            if(h.size()>k) h.poll();
        }
        int[] ans=new int[k];
        int i =0;
        while(!h.isEmpty()){
            ans[i++]=h.poll();
        }
        return ans;
    }
}
个人小站:http://jun10ng.work/ 拥抱变化,时刻斗争,走出舒适圈。
原文地址:https://www.cnblogs.com/Jun10ng/p/12355080.html