Java實現 LeetCode 295 數據流的中位數

295. 數據流的中位數

中位數是有序列表中間的數。若是列表長度是偶數,中位數則是中間兩個數的平均值。java

例如,算法

[2,3,4] 的中位數是 3數據結構

[2,3] 的中位數是 (2 + 3) / 2 = 2.5ide

設計一個支持如下兩種操做的數據結構:優化

void addNum(int num) - 從數據流中添加一個整數到數據結構中。
double findMedian() - 返回目前全部元素的中位數。
示例:spa

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
進階:設計

若是數據流中全部整數都在 0 到 100 範圍內,你將如何優化你的算法?
若是數據流中 99% 的整數都在 0 到 100 範圍內,你將如何優化你的算法?code

class MedianFinder {

   PriorityQueue<Integer> min ;
    PriorityQueue<Integer> max ;
    /** initialize your data structure here. */
    public MedianFinder() {
        min = new PriorityQueue<>();
        max = new PriorityQueue<>((a,b) -> {return  b - a ;});
    }
    
    public void addNum(int num) {
        max.add(num);
        min.add(max.remove());
        if (min.size() > max.size())
            max.add(min.remove());
    }
    
    public double findMedian() {
        if (max.size() == min.size())
            return (max.peek() + min.peek()) / 2.0;
        else 
            return max.peek();
    }
}

/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
相關文章
相關標籤/搜索