[Sword finger offer] _18 Median in the data stream

Title description

How to get the median in a data stream? If an odd number of values ​​is read from the data stream, the median is the value in the middle after all values ​​are sorted. If an even number of values ​​is read from the data stream, then the median is the average of the middle two numbers after all values ​​are sorted. We use the Insert () method to read the data stream, and the GetMedian () method to get the median of the currently read data.

Problem-solving ideas

The general data flow is represented by an array. There are many ways to get the median. Here we introduce a method with less time complexity, using a C ++ priority queue.
That is to say, the method mentioned in the offer book divides the array logically into two parts, the left is the largest heap, and the right is the smallest heap. We always want to ensure maximum heap largest element to the smallest element less than the minimum heap can , in addition, of course, but also to determine the number of elements in the array is even or odd, to determine if we have to make two stacks The difference in the number of elements in is not greater than 1. Here, we guarantee that the number of elements in the maximum heap can be equal to the number of elements in the minimum heap + 1, but the number of elements in the minimum heap can only be the same as the maximum heap. Then if the number of elements in the two heaps is the same, then it is even, then the median is the sum of the two top elements of the heap divided by 2, if they are not the same, it means that the maximum number of elements in the largest heap is the largest heap top Elements.

Code

class Solution {
    priority_queue<int,vector<int>,less<int>> max;
    priority_queue<int,vector<int>,greater<int>> min;
public:
    void Insert(int num)
    {
        if(max.empty() || num<= max.top())
            max.push(num);
        else
            min.push(num);
        
        //保证两个堆的元素个数之差小于1
        if(max.size() == min.size()+2)
        {
            min.push(max.top());
            max.pop();
        }
        if(max.size()+1 == min.size())
        {
            max.push(min.top()); 
            min.pop();
        }
    }

    double GetMedian()
    { 
        return max.size() == min.size() ? (max.top()+min.top())/2.0 : max.top();
    }
 };
Published 253 original articles · praised 41 · 40,000+ views

Guess you like

Origin blog.csdn.net/liuyuchen282828/article/details/104206135