[leetcode] Find Median from Data Stream

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.


[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:

findMedian() -> 1.5
findMedian() -> 2

Special thanks to @Louis1992 for adding this problem and creating all test cases.

I used the multiset data structure in stl rather than a heap.


class MedianFinder {
    multiset<int> nums;
    multiset<int>::iterator left; //always use left first
    multiset<int>::iterator right;
    // Adds a number into the data structure.
    void addNum(int num) {
        int len = nums.size();
        if(len == 1){
            left = nums.begin();
            if(len % 2 == 1){
                //odd after added
                //disable right, move left
                if(num >= *right){
                    left = right;
                else if(num < *left){
                    // nothing to do, no need to move left
                    //num is between left and right
                    //or num is equal to left
                    //move left to right by one step cause new value would add to the tail of current value
                    left++; //move left to point to num
                //even after added, move left and set right
                if(num >= *left){
                    right = ++left;
                    right = left;
                    left --;

    // Returns the median of current data stream
    double findMedian() {
        if(nums.size() % 2 == 1){
            return (double)*left;
            return (double)(*left + *right) / 2;

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


Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.