数字是随机生成并传递给方法的。编写一个程序,在生成新值时查找并维护中值。
堆大小可以相等,或者下面的堆有一个额外的堆。
private Comparator<Integer> maxHeapComparator, minHeapComparator;
private PriorityQueue<Integer> maxHeap, minHeap;
public void addNewNumber(int randomNumber) {
if (maxHeap.size() == minHeap.size()) {
if ((minHeap.peek() != null) && randomNumber > minHeap.peek()) {
maxHeap.offer(minHeap.poll());
minHeap.offer(randomNumber);
} else {
maxHeap.offer(randomNumber);
}
}
else { // why the following block is correct?
// I think it may create unbalanced heap size
if(randomNumber < maxHeap.peek()) {
minHeap.offer(maxHeap.poll());
maxHeap.offer(randomNumber);
}
else {
minHeap.offer(randomNumber);
}
}
}
public static double getMedian() {
if (maxHeap.isEmpty()) return minHeap.peek();
else if (minHeap.isEmpty()) return maxHeap.peek();
if (maxHeap.size() == minHeap.size()) {
return (minHeap.peek() + maxHeap.peek()) / 2;
} else if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
} else {
return minHeap.peek();
}
}
假设解决方案是正确的,那么我不明白为什么代码块(参见我的注释)可以保持堆大小平衡换句话说,两个堆的大小差是0或1。
Let us see an example, given a sequence 1, 2, 3, 4, 5
The first random number is **1**
max-heap: 1
min-heap:
The second random number is **2**
max-heap: 1
min-heap: 2
The third random number is **3**
max-heap: 1 2
min-heap: 3 4
The fourth random number is **4**
max-heap: 1 2 3
min-heap: 4 5
谢谢你
最佳答案
在按照给定的顺序运行之后,
max-heap : 1, 2, 3
min-heap : 4, 5
因为最大堆大小大于最小堆,所以它返回3作为中间值。
最大堆存储大约有一半的元素,而MIN堆大约存储右半部分。
此代码偏向左半部分,即最大堆。
我不明白为什么这个代码不正确。