Monday, August 7, 2017

[Leetcode] Find Median from Data Stream, Solution

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:
```addNum(1)
findMedian() -> 1.5
findMedian() -> 2```

[Thoughts]

[Code]
``````1:  class MedianFinder {
2:  public:
3:    priority_queue<int> min_h;
4:    priority_queue<int, std::vector<int>, std::greater<int>> max_h;
5:    /** initialize your data structure here. */
6:    MedianFinder() {
7:
8:    }
9:
11:      min_h.push(num);
12:      max_h.push(min_h.top());
13:      min_h.pop();
14:      if(min_h.size() < max_h.size()) {
15:        min_h.push(max_h.top());
16:        max_h.pop();
17:      }
18:    }
19:
20:    double findMedian() {
21:      if(min_h.size() > max_h.size()) return min_h.top();
22:      return (double)(min_h.top() + max_h.top())/2;
23:    }
24:  };
25:
26:  /**
27:   * Your MedianFinder object will be instantiated and called as such:
28:   * MedianFinder obj = new MedianFinder();