295 Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.

For example:

add(1)
add(2)
findMedian() -> 1.5
add(3) 
findMedian() -> 2

Solution

class MedianFinder {
public:
    // left to store smaller half
    // right to store larger half
    priority_queue<int> left, right;
    // Adds a number into the data structure.
    void addNum(int num) {
        int leftTop, rightBottom;
        if ( left.size() == 0 ) leftTop = INT_MAX;
        else leftTop = left.top();
        if ( num <= leftTop ) left.push(num);
        else right.push(-num);
        int nl = left.size(), nr = right.size();
        if ( nl == nr or nl == nr+1 ) return;
        while ( nl <= nr-1 ) {
            int tmp = -right.top();
            right.pop();
            left.push(tmp);
            nl++; nr--;
        }
        while ( nl >= nr+2 ) {
            int tmp = left.top();
            left.pop();
            right.push(-tmp);
            nl--; nr++;
        }
        return;
    }

    // Returns the median of current data stream
    double findMedian() {
        if ( left.size() == right.size() ) return (left.top() - right.top())/double(2);
        return left.top();
    }
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf;
// mf.addNum(1);
// mf.findMedian();

Notes

  • Note to use priority_queue, which functions as a heap. Largest element first out! Store negative of a number to enable "smallest element first out".

results matching ""

    No results matching ""