用PriorityQueue类构造大根堆和小根堆-Java

啥是PriorityQueue

PriorityQueue(优先队列),一个基于优先级堆的无界优先级队列。
实际上是一个堆(不指定Comparator时默认是小顶堆),通过传入自定义的compara函数可以实现大顶堆。

啥是堆

1、大顶堆:头部为堆中最大的值
2、小顶堆:头部为队中最小的值
3、PriorityQueue:一个具有优先级的队列,该优先级使得队列始终按照自然顺序进行排序,队列的头部为最小值。

如何用

构建小根堆。
PriorityQueue small=new PriorityQueue<>();
构建大根堆。
PriorityQueue pq = new PriorityQueue((a, b) -> b - a);

例子

力扣
1046. 最后一块石头的重量
有一堆石头,每块石头的重量都是正整数。

每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/last-stone-weight

这个是大根堆,小根堆等我碰到我接着回来总结。

public static void main(String[] args) {
    
    
        TestWk testWk = new TestWk();
        int[] arr = {
    
    2,7,4,1,8,1};
        int c = testWk.lastStoneWeight(arr);
        System.out.println(c);

    }
    public int lastStoneWeight(int[] stones) {
    
    
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a, b) -> b - a);
        for (int stone : stones) {
    
    
            pq.offer(stone);
        }
        while (pq.size() > 1) {
    
    
            int a = pq.poll();
            int b = pq.poll();
            if (a > b) {
    
    
                pq.offer(a - b);
            }
        }
        //三目运算符,判断pq里面还有没有数据了,没有就返回0,有就返回最后一个。
        return pq.isEmpty() ? 0 : pq.poll();
    }

猜你喜欢

转载自blog.csdn.net/weixin_45906830/article/details/112246528