/*
Find Median from Data Stream My Submissions QuestionEditorial Solution
Total Accepted: 17140 Total Submissions: 77162 Difficulty: Hard
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.5
add(3) 
findMedian() -> 2
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

Hide Company Tags Google
Hide Tags Heap Design
*/
class MedianFinder {

    public PriorityQueue<Integer> maxQ = new PriorityQueue<Integer>(11,Collections.reverseOrder());
    public PriorityQueue<Integer> minQ = new PriorityQueue<Integer>();
    // Adds a number into the data structure.
    public void addNum(int num) {//2

        if(maxQ.size()==minQ.size()){
            if(maxQ.size()==0)maxQ.offer(num);//2 ; null
            else if(num<=minQ.peek())maxQ.offer(num);
            else {minQ.offer(num);maxQ.offer(minQ.poll());}
        }
        else if(maxQ.size()<minQ.size()){
            if(num>minQ.peek()){
                minQ.offer(num);
                maxQ.offer(minQ.poll());
            }
            else maxQ.offer(num);
        }
        else{// 2; null
            if(num<maxQ.peek()){
                maxQ.offer(num);
                minQ.offer(maxQ.poll());
            }
            else minQ.offer(num);//2;3
        }
    }

    // Returns the median of current data stream
    public double findMedian() {
        //System.out.println(maxQ.size()+" "+minQ.size());
        if(maxQ.size()>minQ.size())return (double)maxQ.peek();//2
        else{
            if(maxQ.size()==0)return 0;
            //System.out.println("peek: "+maxQ.peek()+" "+minQ.peek());
            return (double)((maxQ.peek()+minQ.peek())/2.0);
        }
    }
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();

Create Find_Median_from_Data_Stream.java