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 is3
[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() -> 2Credits:
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 { public: 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) { nums.insert(num); int len = nums.size(); if(len == 1){ left = nums.begin(); } else{ 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 } else{ //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 } } else{ //even after added, move left and set right if(num >= *left){ right = ++left; left--; } else{ right = left; left --; } } } } // Returns the median of current data stream double findMedian() { if(nums.size() % 2 == 1){ //odd return (double)*left; } else{ return (double)(*left + *right) / 2; } } }; // Your MedianFinder object will be instantiated and called as such: // MedianFinder mf; // mf.addNum(1); // mf.findMedian();