首页 > 其他 > 详细

leetcode-面试题40

时间:2020-03-21 05:26:56      阅读:57      评论:0      收藏:0      [点我收藏+]

这个题用Java的一些特殊数据结构来做是很简单的,如果加一个思想就是最大堆思想。

 

class Solution {
    public int[] getLeastNumbers(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 e : arr) {
            if (heap.isEmpty() || heap.size() < k || e < heap.peek()) {
                heap.offer(e);
            }
            if (heap.size() > k) {
                heap.poll(); 
            }
        }

        int[] res = new int[heap.size()];
        int j = 0;
        for (int e : heap) {
            res[j++] = e;
        }
        return res;
    }
}

end

leetcode-面试题40

原文:https://www.cnblogs.com/CherryTab/p/12535825.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!