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.

For example,

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

Example:

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

 用两个heap来存所有的元素,maxHeap<-小的一部分;minHeap<-大的部分
 
 1 class MedianFinder {
 2 public:
 3     /** initialize your data structure here. */
 4     MedianFinder() {
 5         
 6     }
 7     
 8     void addNum(int num) {
 9         //insert this number
10         if((maxHeap.empty())||(num<=maxHeap.top())){
11             maxHeap.push(num);
12         }else{
13             minHeap.push(num);
14         }
15         
16         //resize the heap
17         while(maxHeap.size()>minHeap.size()+1){
18             minHeap.push(maxHeap.top());
19             maxHeap.pop();
20         }
21         
22         while(minHeap.size()>maxHeap.size()){
23             maxHeap.push(minHeap.top());
24             minHeap.pop();
25         }
26     }
27     
28     double findMedian() {
29         if(maxHeap.size()==minHeap.size()){
30             return 0.5*(maxHeap.top()+minHeap.top());
31         }
32         
33         return maxHeap.top();
34     }
35 private:
36     priority_queue<int> maxHeap;                            //store smaller numbers; (n+1)/2
37     priority_queue<int,vector<int>,greater<int>> minHeap;   //store larger numbers;  n/2
38 };
39 
40 /**
41  * Your MedianFinder object will be instantiated and called as such:
42  * MedianFinder obj = new MedianFinder();
43  * obj.addNum(num);
44  * double param_2 = obj.findMedian();
45  */

猜你喜欢

转载自www.cnblogs.com/ruisha/p/9301571.html
今日推荐