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:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
Solution:Heap
思路:
Time Complexity:
Add: O(log n)
find: O(1)
Space Complexity: O(N)
Solution Code:
class MedianFinder {
// Max-heap small has the smaller half of the numbers.
// Min-heap large has the larger half of the numbers.
PriorityQueue<Integer> minheap;
PriorityQueue<Integer> maxheap;
public MedianFinder() {
minheap = new PriorityQueue<>();
maxheap = new PriorityQueue<>(Collections.reverseOrder());
}
public void addNum(int num) {
if (maxheap.isEmpty() || num < maxheap.peek()) {
maxheap.offer(num);
} else {
minheap.offer(num);
}
if (Math.abs(minheap.size() - maxheap.size()) <= 1) return;
if (maxheap.size() > minheap.size()) minheap.offer(maxheap.poll());
else maxheap.offer(minheap.poll());
}
public double findMedian() {
if (maxheap.size() == minheap.size()) return (double)(minheap.peek() + maxheap.peek()) / 2;
if (maxheap.size() > minheap.size()) return maxheap.peek();
else return minheap.peek();
}
}