有效地找到随机序列的中值

时间:2011-04-14 20:32:46

标签: java algorithm

随机生成数字并将其传递给方法。编写程序以在生成新值时查找并维护中值。

堆大小可以相等,或者下面的堆有一个额外的。

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

谢谢

1 个答案:

答案 0 :(得分:2)

通过给定的序列运行后,

max-heap : 1, 2, 3
min-heap : 4, 5

因为最大堆大小是> min-heap它返回3作为中位数。

max-heap存储大约左半部分元素,而min-heap存储序列的右半部分。

这段代码偏向左半边是max-heap。

我不明白为什么这段代码不正确。