当前位置: 代码迷 >> python >> 合并堆的复杂性
  详细解决方案

合并堆的复杂性

热度:86   发布时间:2023-06-14 08:58:26.0

给定2个最大堆h1h2 ,我想将它们合并为单个最大堆H 我已经完成了相关的问题,并了解合并它们的O(n)方法:只需连接数组并再次调用build_max_heap

但是,我一直在考虑这个算法,在我看来,这是O(logn)并且也是正确的。 有人可以表明它是否不正确,或者它的复杂性是否也归结为O(n)

算法

def merge(h1, h2):
    # base cases, if one of them is a leaf node.
    if h1.right_child is None and h1.left_child is None:
        insert(h1, h2) # insert h1 in h2
        return h2
    if h2.right_child is None and h2.left_child is None:
        insert(h2, h1) # insert h2 in h1
        return h1

    if value(h1) > value(h2):
        new = h1
        orphan1, orphan2 = h1.left_child, h1.right_child
        new.left_child = max(orphan1, orphan2)
        new.right_child = merge(min(orphan1, orphan2), h2)
    else:
        new = h2
        orphan1, orphan2 = h2.left_child, h2.right_child
        new.left_child = max(orphan1, orphan2)
        new.right_child = merge(min(orphan1, orphan2), h1)

    return new

似乎这只穿过了整个深度两次。 这是不正确的?

如果你的堆没有任何平衡要求,那么在O(log(n))中合并两个二进制堆是很简单的。 合并过程与刚刚删除根之后修复堆的过程非常相似。

对于二进制堆的通常实现,其中所有元素连续存储在数组中,平衡要求意味着您的想法不起作用。 它会在阵列中留下一堆洞。

  相关解决方案