给定2个最大堆h1
和h2
,我想将它们合并到一个最大堆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))中合并两个二进制堆就很简单了。合并过程与删除根后修复堆的过程几乎相同。在
对于通常的二进制堆实现,所有元素都连续存储在一个数组中,平衡要求意味着你的想法行不通。它会在阵列中留下一堆洞。在
相关问题 更多 >
编程相关推荐