【LeetCode 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

Follow up:

If all integer numbers from the stream are between 0 and 100, how would you optimize it?
If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

思路

一個最大堆一個最小堆,維護兩個堆中元素個數差小於等於1。

代碼

class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {
        maxnum = 0;
        minnum = 0;
    }
    
    void addNum(int num) {
        if (maxnum == minnum) {
            if (!minHeap.empty() && num > minHeap.top()) {
                int tmp = minHeap.top();
                minHeap.pop();
                minHeap.push(num);
                num = tmp;
            }
            maxHeap.push(num);
            maxnum++;
        }else {
            if (num < maxHeap.top()) {
                int tmp = maxHeap.top();
                maxHeap.pop();
                maxHeap.push(num);
                num = tmp;
            }
            minHeap.push(num);
            minnum++;
        }
    }
    
    double findMedian() {
        if (maxnum == minnum && maxnum != 0) {
            return (maxHeap.top() + minHeap.top()) * 1.0 / 2;
        }else if (maxnum != 0) {
            return maxHeap.top();
        }
        return 0.0;
    }
    
private:
    priority_queue<int, vector<int>, less<int> > maxHeap;
    priority_queue<int, vector<int>, greater<int> > minHeap;
    int maxnum, minnum;
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章