# Median Finder

This page explains Java solution to problem `Median Finder` using `Priority Queue` data structure.

## Problem Statement

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:

• 1. `void addNum(int num)` - Add a integer number from the data stream to the data structure.
• 2. `double findMedian()` - Return the median of all elements so far.
Example 1:

findMedian() -> 1.5
findMedian() -> 2

## Solution

If you have any suggestions in below code, please create a pull request by clicking here.
``````
package com.vc.hard;

import java.util.*;

class MedianFinder {

/** initialize your data structure here. */
PriorityQueue<Integer> left;
PriorityQueue<Integer> right;

public MedianFinder() {
left = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer p, Integer q) {
return Integer.compare(q, p);
}
});
right = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer p, Integer q) {
return Integer.compare(p, q);
}
});
}

if(left.size() <= right.size()) {
right.offer(num);
left.offer(right.poll());
}
else {
left.offer(num);
right.offer(left.poll());
}
}

public double findMedian() {
if(left.size() == right.size()) return (double)(left.peek() + right.peek()) / 2;
else return left.peek();
}
}

/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();