[LeetCode] Find Median from Data Stream

来源:互联网 发布:问道登陆器源码 编辑:程序博客网 时间:2024/06/06 00:38

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.

Examples: 

[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.

For example:

addNum(1)addNum(2)findMedian() -> 1.5addNum(3) findMedian() -> 2


代码如下:

public class MedianFinder {PriorityQueue<Integer> max;PriorityQueue<Integer> min;    /** initialize your data structure here. */    public MedianFinder() {        max=new PriorityQueue<Integer>(1000,Collections.reverseOrder());        min=new PriorityQueue<Integer>();    }        public void addNum(int num) {    if(min.isEmpty()||min.peek()<num) min.add(num);    else max.add(num);    if(min.size()<max.size()) min.add(max.poll());    if(max.size()<min.size()-1) max.add(min.poll());    }        public double findMedian() {        if(max.size()==min.size()) return (max.peek()+min.peek())/2.0;        else return min.peek();    }}/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */