295. 数据流的中位数

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:

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

找出数据流中的中位数。题意是给一个数据流,请根据题意设计几个函数。

其中需要实现的函数是addNum()和findMedian()。

思路:

 [2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5

优先队列:PriorityQueue api:(add,poll,peek,size(),isEmpty())
1、准备两个优先队列,一个当小根堆,一个当大根堆
2、当加入一个数时,如果大根堆为空或小于等于大根堆堆顶,则加入到大根堆中,否则加入到小根堆中
并且同时调整一下大小堆的数量
调整规则如下:
两堆的数量差不能大过1,如果数量差大于1,则数量多的堆弹出头节点加入到数量小的堆中

3、获取中位数:如果两堆的数量相等,中位数等于两堆顶的元素相加/2.0,否则等于数量多的堆的堆顶

注意:返回的类型是double,所以如果数组流是even是,除的是2.0,不是2

class MedianFinder {

    private PriorityQueue<Integer> minHeap;
    private PriorityQueue<Integer> maxHeap;

    /** initialize your data structure here. */
    public MedianFinder() {
        minHeap=new PriorityQueue<>();
        maxHeap=new PriorityQueue<>((a,b)->b-a);
    }

    private void modifyHeapSize(){
        if(minHeap.size()==maxHeap.size()+2){
            maxHeap.add(minHeap.poll());
        }
        if(maxHeap.size()==minHeap.size()+2){
            minHeap.add(maxHeap.poll());
        }
    }
    
    public void addNum(int num) {
        if(maxHeap.isEmpty()||num<=maxHeap.peek()){
            maxHeap.add(num);
        }else{
            minHeap.add(num);
        }

        modifyHeapSize();
    }
    
    public double findMedian() {
        if(minHeap.size()==maxHeap.size()){
            return (minHeap.peek()+maxHeap.peek())/2.0;
        }
        return maxHeap.size()>minHeap.size()?maxHeap.peek():minHeap.peek();
    }
}

  

 

posted @ 2021-08-30 11:42  sherry001  阅读(48)  评论(0编辑  收藏  举报