Press "Enter" to skip to content

花花酱 Amortized Analysis 均摊分析 SP7

Amortized Analysis

Amortized analysis can help us understand the actual cost of n operations on a data structure. Since some operations can be really fast e.g. O(1), but some operations can be really slow e.g. O(n). We could say the time complexity of that operation is O(n). However, it does not reflect the actual performance. And turns out, we can prove that certain operations have an amortized cost of O(1) while they can take O(n) in the worst case.

均摊分析可以帮助我们了解对一个数据结构进行n次操作的真实代价。对于相同的操作,有时候可以非常快,例如在O(1)时间内完成,而有时候则需要O(n)。我们当然可以说这个操作最坏情况下的时间复杂度是O(n),但是这并不能真实反映它的实际复杂度。通过均摊分析,我们可以证明,尽管有些操作在最坏情况下是O(n)的时间复杂度,但是均摊下来只需要O(1)。

 

Dynamic Array

dynamic array doubles its size when it’s full which could take O(i) time where i is the number of elements in the array. Otherwise just store the element which only cost O(1). We can use aggregate method to compute the amortized cost of dynamic array.

动态数组在容量满时将容量翻翻,这一步需要O(i)时间,i是当前数组中的元素个数。如果没有满,只需要将元素存储下来即可,只需要花费O(1)时间。我们可以使用聚合法来计算均摊成本。

((1 + 1) + (1 + 2) + (1) + (1 + 4) + (1) + (1) + (1) + (1+8) + … + (1+n)) / n, assuming n is 2^k.

= (1 * n + (1 + 2 + 4 + 8 + … + n)) / n = (n + 2n – 1) / n = 3. O(1)

C++

Output

 

Monotonic Stack

例子2: 单调栈

往单调栈push一个元素的时候,会删除上所有小于等于它的元素。这步操作在最优情况下是O(1)时间,如果它比栈顶元素要小。在最坏情况下是O(i)时间,栈上有i个元素,它比这i个元素都要大,所以一共要pop i次。

聚合法:

由于每个元素都会被push到栈上去1次,最多会被pop1次,所以总的操作数 <= 2n。 2n / n = 2 O(1)。

会计法:

每次push之前先存k块钱,k=2, 一块钱用于push自己,一块钱留着用于pop自己。

push的时候扣除1块钱,pop的时候再扣除1块钱。但不管怎样,我的账户上的钱永远>=0。这样我们可以说push的均摊成本是k=2。同样是O(1),尽管它的worst case是O(n)。

C++

Output

 

Related Problem

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

Be First to Comment

Leave a Reply