像最大堆和最小堆一樣,我想實現一箇中間堆來跟蹤給定整數集的中值。該API應具有以下三個功能:如何實現中間堆
insert(int) // should take O(logN)
int median() // will be the topmost element of the heap. O(1)
int delmedian() // should take O(logN)
我想用一個數組(一)實施來實現,其中數組索引k的孩子都存儲在數組的下標堆2 * k和2 * K + 1.爲了方便起見,數組開始填充索引1中的元素。 這是我到目前爲止: 中位數堆將有兩個整數來跟蹤目前插入的整數數量>當前中位數(gcm)和<目前的中位數(lcm)。
if abs(gcm-lcm) >= 2 and gcm > lcm we need to swap a[1] with one of its children.
The child chosen should be greater than a[1]. If both are greater,
choose the smaller of two.
對於其他情況類似。我無法想出如何下沉和游泳元素的算法。我認爲應該考慮到數量如何接近中位數,所以像:
private void swim(int k) {
while (k > 1 && absless(k, k/2)) {
exch(k, k/2);
k = k/2;
}
}
我不能拿出完整的解決方案,但。
這將讓困難沒有限制任何給定值的多樣性。 – greybeard 2016-10-31 11:24:58