algorithm - 关于Min Max Heap DeleteMin的时间复杂度
问题描述
在以下关于 min-max heap delete-min 过程的代码片段的 for 循环中,为什么last=(*n)/2
?那是因为在更坏的情况下,必须将 x 插入...的孙子的孙子,例如:树高 5: min max min max min, floor(5/2)=2, 正确因为在最坏的情况下,第一级之后只有两分钟。现在又一个:height 4: min max min max, floor(4/2)=2,这次不行。我认为也许last=(*n)
会起作用,甚至for(i=1;;)
会起作用,因为它只是检查不会发生的事情?标题的原因是 IIRC 最小-最大堆删除的时间复杂度是,
O(log n)
但(*n)/2
看起来,嗯,就像O(n)
.
element delete_min(element heap[], int *n) {
int i, last, k, parent;
element temp, x;
if (!(*n)) {
// checking
}
heap[0] = heap[1];
x = heap[(*n)--];
for (i=1, last=(*n)/2; i<=last; ) {
k = min_child_grandchild(i, *n);
if (x.key <= heap[k].key)
break;
heap[i] = heap[k];
if (k <= 2*i+1) {
i = k;
break;
}
parent = k/2;
if (x.key > heap[parent].key)
SWAP(heap[parent], x, temp);
i = k;
} // end for
heap[i] = x;
return heap[0];
}
资源:
解决方案
如果在 size 范围内线性迭代n
,则循环执行 O(n) 次。这里的线性意味着你有一些循环索引,每次循环都会通过添加一个常数来修改,通常但不一定是 1:
for(i = 0; i < n; i += c) { /* Loop executes O(n) times */ }
但这不是这里发生的事情。i
没有被常数递增。它被设置为的某个子或孙的索引k
在哪里。其索引最小的孩子在 index ;索引最小的孙子位于 index 。(这些公式适用于基于 1 的索引,这在算法描述中很常见。)k
i
i
2i
4i
所以循环更像这样(其中常数c
通常为 4 但绝不小于 2):
for(i = 0; i < n; i *= c) { /* Loop executes O(log n) times */ }
推荐阅读
- flutter - Flutter - 在底部附近按下 FlatButton
- java - Exoplayer 活动不播放视频,而是显示空白屏幕
- python - 只需要在 for 循环外打印一次
- powerbi - 如何使用第一列中的给定字符串匹配条件在power bi中创建新列并从另一列获取值,创建新列?
- sql - 计数 SQL 查询协助
- performance - JMeter 发送的请求少于预期
- html - 如何从 vue web 应用程序项目中删除未知请求
- algorithm - 给定圆上图的节点,找到要删除的最小节点数以获得一个图,其中每个节点都有到下一个节点的边
- javascript - 将复利计算器的未来价值计算转换为javascript
- pyspark - pyspark randomsplit 返回 null