1. 程式人生 > 其它 >Leetcode 295-資料流的中位數

Leetcode 295-資料流的中位數

技術標籤:演算法

腦子裡建立如下動態的過程:為了找到新增新資料以後,資料流的中位數,我們讓新資料在最大堆和最小堆中都走了一遍。而為了讓最大堆的元素多 1 個,我們讓從最小堆中又拿出一個元素「送回」給最大堆;

class MedianFinder {
 
    //當前大堆頂和小堆頂的元素個數之和
    private int count;
    private PriorityQueue<Integer> maxheap;
    private PriorityQueue<Integer> minheap;

    /** initialize your data structure here. */
    public MedianFinder() {
        count=0;
        maxheap=new PriorityQueue<>((x,y)->y-x);
        minheap=new PriorityQueue<>();
    }
    
    public void addNum(int num) {
        count+=1;
        maxheap.offer(num);
        minheap.offer(maxheap.poll());
        if(count%2!=0){
            maxheap.offer(minheap.poll());
        }
    }
    
    public double findMedian() {
        if(count%2==0){
            return (double)(maxheap.peek()+minheap.peek())/2;
        }else{
            return (double)maxheap.peek();
        }
    }

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

在這裡插入圖片描述