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)
addNum(2)
findMedian() -> 1.5
addNum(3) 
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:      
10:    void addNum(int num) {  
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();  
29:   * obj.addNum(num);  
30:   * double param_2 = obj.findMedian();  
31:   */  


No comments: