Cattle off - median data stream

Title describes
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.
Solution:
1, declare a vector array
2, to each vector in the num array push_back a function insert
3, the length of the array is calculated, the odd values of the intermediate output, otherwise the output value of the average of the two middle

class Solution {
    vector<int> array;
public:
    void Insert(int num)
    {
        array.push_back(num);
    }

    double GetMedian()
    { 
        sort(array.begin(), array.end());
        int length = array.size();
        if (length%2==0)
            return double((array[length/2]+array[length/2-1]))/2;
        else
            return double(array[length/2]);
    }
};
Published 315 original articles · won praise 119 · views 110 000 +

Guess you like

Origin blog.csdn.net/w144215160044/article/details/105004975