剑指 Offer 41. 数据流中的中位数

剑指 Offer 41. 数据流中的中位数


class MedianFinder {

    /** initialize your data structure here. */
    PriorityQueue<Integer> maxHeap; //大顶堆
    PriorityQueue<Integer> minHeap;  //小顶堆
    public MedianFinder() {
        maxHeap=new PriorityQueue<>((n1,n2)->(n2-n1));
        minHeap=new PriorityQueue<>();
    }
    
    int count=0;
    public void addNum(int num) {
        if(count%2==0){          //当为偶数的时候,放到最大堆
            maxHeap.offer(num);
            int max=maxHeap.poll();
            minHeap.offer(max);
        }else{                   //当为奇数的时候,放到最小堆
            minHeap.offer(num);
            int min=minHeap.poll();
            maxHeap.offer(min);

        }
        count++;
    }
    
    public double findMedian() {
        if(count%2==0){
            return (minHeap.peek()+maxHeap.peek())/2.0;
        }else{
            return minHeap.peek();
        }

    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
上一篇:C#中的委托和事件详解


下一篇:iOS开发之SQLite-C语言接口规范(二) —— Prepared Your SQL Statements