295 - Find Median from Data Stream

解法一 - Two Heaps

這個解法真的有夠聰明的,讓我們來看看說明:

讓我們過一個範例來了解這個演算法:

1. insertNum(3)
2. insertNum(1)
3. findMedian() -> output: 2
4. insertNum(5)
5. findMedian() -> output: 3
6. insertNum(4)
7. findMedian() -> output: 3.5

讓我們假設有奇數個 element 時,max heap 會比 min heap 多存一個 element,以下是步驟:

程式碼實作如下:

class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {
    }

    void addNum(int num) {
        if(maxHeap.empty() or num <= maxHeap.top()) {
            maxHeap.push(num);
        }
        else {
            minHeap.push(num);
        }

        if( maxHeap.size() > minHeap.size() + 1) {
            minHeap.push(maxHeap.top());
            maxHeap.pop();
        }
        else if( minHeap.size() > maxHeap.size() ) {
            maxHeap.push(minHeap.top());
            minHeap.pop();
        }
    }

    double findMedian() {
        if(maxHeap.size() == minHeap.size()) {
            return maxHeap.top() / 2.0 + minHeap.top() / 2.0;
        }

        return maxHeap.top();
    }

private:
    priority_queue<int, vector<int>, greater<int>> minHeap;
    priority_queue<int> maxHeap;
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */

results matching ""

    No results matching ""