algorithm - Intersection of two maximum heaps -
i have 2 maximum-heaps (represented in arrays), h1 of size m , h2 of size n, n>m. have create third max-heap elements coming intersection of h1 , h2.
the elementary solution (scan 2 arrays) takes o(n*m) time, , doesn't take advantage of max-heap properties.
other ideas?
given 2 heaps, can compute intersection of elements in o(m log m + n log n) time, , result ordered. ordered array heap, no further time required.
python-syntax example:
# given arrays heap1, heap2. intersection = [] while len(heap1) > 0 , len(heap2) > 0: if heap1[0] == heap2[0]: # common element, part of intersection. intersection.append(heap1[0]) heap.heappop(heap1) heap.heappop(heap2) elif heap1[0] > heap2[0]: heap.heappop(heap1) else: heap.heappop(heap2) # intersection contains common elements of heap1 , heap2, # in max-to-min order, meets heap invariant.
Comments
Post a Comment