Leetcode[295] Find Median from Data Stream
05 Dec 2015###Task1 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
###Java
class MedianFinder {
class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer i1, Integer i2) {
return i2.compareTo(i1);
}
}
private PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new MyComparator());
// Adds a number into the data structure.
public void addNum(int num) {
if (minHeap.size() == maxHeap.size()) {
if (minHeap.peek() != null && num > minHeap.peek()) {
maxHeap.offer(minHeap.poll());
minHeap.offer(num);
} else {
maxHeap.offer(num);
}
} else {
if (num < maxHeap.peek()) {
minHeap.offer(maxHeap.poll());
maxHeap.offer(num);
} else {
minHeap.offer(num);
}
}
}
// Returns the median of current data stream
public double findMedian() {
if (minHeap.size() == maxHeap.size()) {
return (double) (minHeap.peek() + maxHeap.peek()) / 2;
} else {
return (double) maxHeap.peek();
}
}
};
// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();
###Points
- maxHeap contains small number so maxHeap.peek() will return the largest number in the small group and vice versa.
- in this design, maxHeap is not smaller than the minHeap. (easier implemented)