【问题标题】:Finding max element in a min-heap?在最小堆中找到最大元素?
【发布时间】:2014-05-07 08:48:28
【问题描述】:

我现在正在学习堆,显然更多的注意力放在堆的最小元素上,但是我只是想知道如何找到最大元素?对于 min 元素,您只需要返回根,不确定如何处理 max ?

【问题讨论】:

标签: java algorithm


【解决方案1】:

我会假设 Heap 是作为一个数组实现的(这是实现 Heap 的一种非常常见的方式)。

你不需要检查整棵树,“只”一半。

因此,如果我从 1 开始索引数组的元素,二进制文件将如下所示(其中数字是数组中的索引):

              1
         2          3
      4    5     6     7
     8 9 10 11 12 13 

您只需要检查 floor(length(heapArray)/2) 最后一个元素,在 7 以上的情况下,从 7 到 13。之前的节点有子节点,所以它们永远不会是最大值。比意味着检查 n/2 个元素,所以你仍然有 O(n) 复杂度。

【讨论】:

    【解决方案2】:

    定义变量max并将其初始化为0。

    HeapNode[] h;
    int last;
    int max=0;
    

    如果堆不为空,则从 0 级和 0 位置(根)开始,检查最大值并迭代到左右子节点。

    public int getMax() throws Exception {
        if (isEmpty()) {
            Exception EmptyHeapException = new EmptyHeapException();
            throw EmptyHeapException;
        } else {
            //findMax(0, 0);    //If you want to use Iteration
            for(int i=0;i<=last;i++)
                max = Math.max(h[i].key, max);//Updated Thanks Raul Guiu
            return max;
        }
    }
    

    在每个节点上迭代,直到最后一个节点。

    private void findMax(int i, int level) {
        if (i > last) return;
        if(max<h[i].key)
            max=h[i].key;
        findMax(2*i+1, level+1);//left node
        findMax(2*i+2, level+1);//right node
    }
    
    public boolean isEmpty() {
        return (last < 0);
    }
    

    你从堆中获得最大值。

    【讨论】:

    • 您正在检查整个堆。为什么不只检查 (i=0;i
    • @RaulGuiu 你是对的。谢谢。我在答案中更新了我的代码。
    猜你喜欢
    • 2020-05-08
    • 2018-11-29
    • 2012-11-04
    • 1970-01-01
    • 2019-04-11
    • 2021-10-31
    • 2018-06-02
    • 2021-10-10
    • 2015-01-15
    相关资源
    最近更新 更多