295. Find Median from Data Stream 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 an integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

 

思路:觉得没有必要啊,为什么要用Q?大概就是免除了:算中位数还要除以2加1减1之类的烦恼。体会一下Q在排序时的优越性

 

排队Q领offer,所以动词应该是offer

 

class MedianFinder {
    PriorityQueue<Integer> min;
    PriorityQueue<Integer> max;

    /** initialize your data structure here. */
    public MedianFinder() {
        min = new PriorityQueue<Integer>();
        max = new PriorityQueue<Integer>(1000,
                                 Collections.reverseOrder());
    }
    
    public void addNum(int num) {
        max.offer(num);
        min.offer(max.poll());
        
        if (max.size() < min.size()) {
            max.offer(min.poll());
        }
    }
    
    public double findMedian() {
        if (min.size() == max.size()) 
            return (min.peek() + max.peek()) / 2.0;
        else 
            return max.peek();
    }
}
View Code

 

posted @ 2020-09-14 10:29  苗妙苗  阅读(111)  评论(0编辑  收藏  举报