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:

1
2
[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:

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

O(n log n) time O(n) space solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MedianFinder {
// if [2,3,4,5]
PriorityQueue<Integer> large = new PriorityQueue<>(); // [4,5]
PriorityQueue<Integer> small = new PriorityQueue<>((a, b) -> b - a); // [3,2]

// Adds a number into the data structure.
public void addNum(int num) {
large.offer(num);
small.offer(large.poll());
if (large.size() < small.size())
large.add(small.poll());
}

// Returns the median of current data stream
public double findMedian() {
return large.size() > small.size() ? large.peek() : small.peek() + (large.peek() / 2.0 - small.peek() / 2.0);
}
};

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