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

解题思路:

明天早上醒了补充一下,正好复习~

代码:

class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        if(rightHeap.empty()){
            rightHeap.push(num);
        }else{
            int mid = rightHeap.top();
            if(num >= mid){
                rightHeap.push(num);
            }else{
                leftHeap.push(num);
            }
        }
        int diff = rightHeap.size() - leftHeap.size();
        if(diff > 0 && diff > 1){
            int temp = rightHeap.top();
            rightHeap.pop();
            leftHeap.push(temp);
        }else if(diff < 0 ){
            /*cout<<"here "<<endl;
            cout<<"left size = "<<leftHeap.size()<<endl;
            cout<<"right size = "<<rightHeap.size()<<endl;*/
            int temp = leftHeap.top();
            leftHeap.pop();
            rightHeap.push(temp);
        }
    }
    
    double findMedian() {
        if(rightHeap.size() == leftHeap.size()){
            int r = rightHeap.top();
            int l = leftHeap.top();
            return (double)(r + l) / 2.0;
        }
        return (double)rightHeap.top();
    }
private:
    priority_queue<int, vector<int>, less<int>> leftHeap;
    priority_queue<int, vector<int>, greater<int>> rightHeap;
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9116683.html