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 is3
[2,3]
, the median is(2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
For example:
addNum(1)
addNum(2)
findMedian() -
>
1.5
addNum(3)
findMedian() -
>
2
tag: Heap, Priority Queue
class MedianFinder {
PriorityQueue<Integer> leftQ;
PriorityQueue<Integer> rightQ;
Integer mid;
/** initialize your data structure here. */
public MedianFinder() {
leftQ = new PriorityQueue<Integer>((a, b) -> (b - a));
rightQ = new PriorityQueue<Integer>();
mid = null;
}
public void addNum(int num) {
if (mid == null){
mid = num;
}
else if (num > mid){
rightQ.offer(num);
}
else{
leftQ.offer(num);
}
//adjust
while (leftQ.size() - rightQ.size() > 1) {
int removal = leftQ.poll();
rightQ.offer(mid);
mid = removal;
}
while (rightQ.size() - leftQ.size() > 0){
int removal = rightQ.poll();
leftQ.offer(mid);
mid = removal;
}
}
public double findMedian() {
if (leftQ.size() == rightQ.size()){
return mid;
}
else{
if (leftQ.size() > rightQ.size()){
return (double)(leftQ.peek() + mid) / 2;
}
else{
return (double)(rightQ.peek() + mid) / 2;
}
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/