我有两个最大堆(用数组表示),H1的大小为m,H2的大小为n,其中n>m。
我必须创建第三个最大堆,其中元素来自H1和H2的交集。
基本解决方案(扫描两个数组)需要O(n*m)时间,并且不能利用最大堆属性。
还有其他想法吗?
基本解决方案(扫描两个数组)需要O(n*m)时间,并且不能利用最大堆属性。
还有其他想法吗?
给定两个堆,您可以在O(M log M + N log N)时间内计算元素的交集,并且结果是有序的。有序数组已经是一个堆,因此不需要额外的时间。
Python语法示例:
# Given arrays heap1, heap2.
intersection = []
while len(heap1) > 0 and len(heap2) > 0:
if heap1[0] == heap2[0]:
# Common element, part of the intersection.
intersection.append(heap1[0])
heap.heappop(heap1)
heap.heappop(heap2)
elif heap1[0] > heap2[0]:
heap.heappop(heap1)
else:
heap.heappop(heap2)
# intersection now contains the common elements of heap1 and heap2,
# in max-to-min order, so it already meets the heap invariant.
O(m+n)
,交集O(m)
,堆化O(mlgm)
,求和O(n+mlgm)
。为什么这是线性的? - Jason Hu