Median (19) in the data stream

topic

[How to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values ​​after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values ​​of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read. ]


1, analysis of
the data stream into two stacks, respectively, is a maximum stack, a heap is minimal. The maximum stack elements are smaller than the smallest element in the stack, and the number of elements differ by not more than two stack 1, so as to ensure the time when the element is an even number, the median is a maximum and minimum stack in the first stack mean elements. When the element is odd, the median is the first element of the minimum heap.
2, the code

class Solution {
public:
    void Insert(int num)
    {
        //当两个容器中元素和为偶数时,将新的数据插入到最小堆中,奇数时插入到最大堆中
        if(((max.size()+ min.size())&1)==0)
        {
            if(max.size()>0 && num<max[0])
            {
                max.push_back(num);
                push_heap(max.begin(),max.end(),less<int>());
                num=max[0];
                pop_heap(max.begin(),max.end(),less<int>());
                max.pop_back();
            }
            min.push_back(num);
            push_heap(min.begin(),min.end(),greater<int>());
            
        }
        else
        {
            if(min.size()>0 && num>min[0])
            {
                min.push_back(num);
                push_heap(min.begin(),min.end(),greater<int>());
                num=min[0];
                pop_heap(min.begin(),min.end(),greater<int>());
                min.pop_back();
            }
            max.push_back(num);
            push_heap(max.begin(),max.end(),less<int>());
        }
    }

    double GetMedian()
    { 
        int len=max.size()+min.size();
        if(len<=0)
            return 0;
        if((len & 1)==0)
            return (max[0]+min[0])/2.0;
        else
            return min[0];
    
    }
private:
    vector<int> max;
    vector<int> min;
};
Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104718995