【发布时间】:2020-06-04 08:21:58
【问题描述】:
我正在尝试找出以下代码的时间复杂度。
N= number of elements in array
D= a constant: D>1
V= a constant: V>1000
counter=1; //the maximum value of the counter is N/D.
for(i=0; i<N; i++)
{
[OP1] O1_Operation; // O(1) operation. [Total: N times]
[OP2] if(i%D!=0) continue; // O(1) operation. [Total: N times]
[OP3] for(j=0;j<counter;j++) // [Total: {(N/D)*((N/D)+1)}/2 times]
[OP4] for(s=0;s<V;s++)
[OP5] O1_Operation; // O(1) operation. [Total: (V*{(N/D)*((N/D)+1)}/2) times]
[OP6] counter++; // O(1) operation. [Total: N/D times]
}
我添加了每个操作的时间复杂度和它将执行的总次数。这段代码让我感到困惑是因为 mod 操作。这个模组将只允许(N/D)操作来完成代码 OP[3-6]。
对于 [OP3],第一次执行 1 次,第二次执行 2 次,...,N/D 次。因此,执行的总数可以是 [(N/D) * ( (N/D)+1)] /2。因为 D 和 V 是常量而删除它们会导致整个代码的复杂度为 O(N^2)。
这对吗?
【问题讨论】:
-
好吧,最坏情况的复杂性很简单:
O(N * N/D * V)。 -
并且可以进一步将
N * N/D部分限制为N/D * (N/D + 1) / 2。
标签: algorithm time-complexity complexity-theory