问题
I found the topic of min-max heap on Wikipedia. I was wondering if there is any way of building this min-max heap in O(n)
.
I know you can do this with both min heap and max heap, but I'm not sure what would be the approach for this. Inserting an element takes O(log n)
time complexity and I feel like this kind of tree can't be build more efficiently than O(n log n)
.
回答1:
Yes, it can. In your build-heap loop, you simply call TrickleDown
, just like you would with a min heap or a max heap. That function will move the item accordingly, depending on whether it's on a min level or a max level.
See the original paper, Min-Max Heaps and Generalized Priority Queues for general info. The paper doesn't implement build-heap, but if you write your own that calls TrickleDown
, it works as expected. That is:
for i = A.length/2 downto 0
TrickleDown(i)
TrickleDown
determines if i
is on a min level or a max level, and calls the appropriate method, TrickleDownMin
or TrickleDownMax
.
来源:https://stackoverflow.com/questions/47076465/how-to-build-a-min-max-heap-in-on-time-complexity