首页 > 代码库 > 295. Find Median from Data Stream

295. Find Median from Data Stream

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:

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

思路:作业题。用max heap和min heap。max heap存小的那一半数。min heap存大的那一半数。要维护两个size一样。所以max size
> min size当再加数的时候如果比max的最大数小就放在max里面,把max poll放在min,如果大,就直接放在min里面。其余同理两种size情况同理。
public class MedianFinder {    PriorityQueue<Integer> min=new PriorityQueue<Integer>();    PriorityQueue<Integer> max=new PriorityQueue<Integer>((a,b)->(b-a));        // Adds a number into the data structure.    public void addNum(int num) {        if(max.size()==0&&min.size()==0)        {            max.add(num);            return;        }        if(min.size()<max.size())        {            if(max.peek()>num)            {                min.add(max.poll());                max.add(num);            }          else        {            min.add(num);        }        }        else if(min.size()>max.size())        {            if(min.peek()>num)            {                max.add(num);            }            else            {               max.add(min.poll());               min.add(num);            }        }        else        {             if(min.peek()>num)            {                max.add(num);            }            else            {               max.add(min.poll());               min.add(num);            }        }    }    // Returns the median of current data stream    public double findMedian() {        double res=0;        if((min.size()+max.size())%2==1)        {            return (double)max.peek();        }        return (double)(max.peek()+min.peek())/2;    }};// Your MedianFinder object will be instantiated and called as such:// MedianFinder mf = new MedianFinder();// mf.addNum(1);// mf.findMedian();

 



295. Find Median from Data Stream