令A [1,…,n]是在每个位置存储一位(1或0)的数组,f(m)是其时间复杂度为θ(m)的函数。考虑以下用C语言编写的程序片段:
counter = 0;
for (i = 1; i < = n; i++)
{
if (A[i] == 1)
counter++;
else {
f(counter);
counter = 0;
}
}
该程序片段的复杂性是
(A) Ω(n 2 )
(B) Ω(nlog n)和O(n 2 )
(C) θ(n)
(D) O(n)答案: (C)
说明:请注意,在else条件内,首先调用f(),然后将counter设置为0。
考虑以下情况:
a) All 1s in A[]: Time taken is Θ(n) as
only counter++ is executed n times.
b) All 0s in A[]: Time taken is Θ(n) as
only f(0) is called n times
c) Half 1s, then half 0s: Time taken is Θ(n) as
only f(n/2) is called once.
这个问题的测验