Algorithm – track the median of the extended array

Interview questions:

The following edit gives you an array You make 2 stacks, one minheap and the other maximum heap Now use the two provided heaps of O (NLog n) time to find the median of the array

Correct the problem. The numbers are randomly generated and stored in the (Extended) array How do you track the median?

This problem can be solved by using 2 heap, and the medium equivalent can be accessed in O (1) time

Solution

Here is how you use these two heaps Note that I assume you don't know the number of elements, which is why we have to eject until we eject from the smallest heap is greater than or equal to what we eject from the largest heap Note that we return the average, because in the case of the set of {1,2,3,4}, the median is actually 2.5 (the average of the two "middle" values) I assume that value types are dual, but this is obviously anything here:

double min = minheap.pop();
double max = maxheap.pop();
while(min < max) {
    min = minheap.pop();
    max = maxheap.pop();
}

return (min + max) / 2;

Because the pop-up is O (log n), we must pop up the O (n / 2) value, which is O (n log n)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>