Big o 考试答案确认-摊销时间
下面的方法op属于一个具有两个私有整数值实例变量n的类 和计数器,它们在构造函数中都被初始化为值零,并且随后仅 用op法修正Big o 考试答案确认-摊销时间,big-o,time-complexity,Big O,Time Complexity,下面的方法op属于一个具有两个私有整数值实例变量n的类 和计数器,它们在构造函数中都被初始化为值零,并且随后仅 用op法修正 public void op() { if(counter<100) { op1(); //method with O(1) time complexity counter++; }else { op2(); //method with O(n^2) time complexity
public void op()
{
if(counter<100)
{
op1(); //method with O(1) time complexity
counter++;
}else {
op2(); //method with O(n^2) time complexity
counter = 0;
}
n++;
}
public void op()
{
如果(counter)在谈到摊销运行时,您可以不计算大部分时间将发生的情况。
首先,你如何定义大部分时间?
操作的摊销运行时间可视为操作的平均运行时间
现在谈谈你的问题:
为简单起见,我假设您编写了if(counter<99)
而不是if(counter<100)
。这样,操作在100个周期后而不是在101个周期后重复
当写O(…)
时,在下面,我实际上是指O(…)
,因为否则你的问题的答案将是微不足道的,因为O(1)
的一切也是O(n^2)
调用op()
100次后,总运行时间将为99+100^2
调用op()
200次后,总运行时间将是2*99+100^2+200^2
现在让我们忘记那些99
或2*99
,因为它们由n^2
值控制。
因此,在调用op()
n
次之后,总运行时间大约为100^2+200^2+…+n^2
(为简单起见,假设n
可被100
整除)
现在我将展示这是在O(n^3)
中
Let k = n/100
100^2 + 200^2 + ... + n^2
= 100^2 * (1^2 + 2^2 + ... + k^2)
=(*) O(100^2 * k * k^2)
= O(k^3)
= O(n^3)
(*): sum from 1 to k of i^2 is k (k+1) (2k+1) / 6 = O(k^3)
最后,op()
的平均运行时间是O(n^3/n)=O(n^2)
。因此,op()
的摊销运行时间是O(n^2)
哇,你不仅解释了,甚至证明了你的答案。