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
思路:这里我们用两个heap来存储数据,一个最大堆,一个最小堆,分成三种情况s - s, s + 1 - s, s - s + 1讨论。
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> (o2 - o1));
PriorityQueue<Integer> minHeap = new PriorityQueue<>((o1, o2) -> (o1 - o2));
public MedianFinder() {
}
public void addNum(int num) {
if (maxHeap.isEmpty() || num < maxHeap.peek()) {
maxHeap.offer(num);
} else {
minHeap.offer(num);
}
if (maxHeap.size() == minHeap.size() + 2) {
minHeap.offer(maxHeap.remove());
}
if (maxHeap.size() + 2 == minHeap.size()) {
maxHeap.offer(minHeap.remove());
}
}
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
} else {
return minHeap.peek();
}
}
heap的第二种写法,分为两种情况考虑,只有s - s和s + 1 - s。
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> (o2 - o1));
PriorityQueue<Integer> minHeap = new PriorityQueue<>((o1, o2) -> (o1 - o2));
public MedianFinder() {
}
public void addNum(int num) {
if (!minHeap.isEmpty() && minHeap.peek() < num) {
maxHeap.offer(minHeap.remove());
minHeap.offer(num);
} else {
maxHeap.offer(num);
}
if (maxHeap.size() == minHeap.size() + 2) {
minHeap.offer(maxHeap.remove());
}
}
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else {
return maxHeap.peek();
}
}