📜  门| GATE-CS-2004 |第 82 题

📅  最后修改于: 2021-09-27 06:04:46             🧑  作者: Mango

设 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.

这个问题的测验