【问题标题】:What is the time complexity of this question?这个问题的时间复杂度是多少?
【发布时间】:2020-02-21 17:30:16
【问题描述】:

这段代码的时间复杂度是多少?

int count=0;

for(int I=N;I>0;I=I/2)

{

for(int j=0;j<I;j++)

   {

      count=count+1;

    }

}

请解释清楚

【问题讨论】:

  • 谁能给我建议,如何提问??那个问题的错误是什么?因为每当我提出问题时,我都会投反对票?

标签: data-structures time-complexity


【解决方案1】:

内部循环进行 n 次迭代,然后是 n/2,然后是 n/4,等等。

i =n   n/2      n/4    n/8  ....................logn times

j=n     n/2     n/4    n/8 ...........logn tmes

T(n) = n+ n/2 + n/4 + n/8 + ...........logn time
       = n(1+ 1/2 + 1/4 + .............logn times) Decreasing GP
     =O(n)

因此,

时间复杂度为O(n)

要了解有关几何系列的更多信息,请参阅document

这里让我们举个例子:

让 n = 10

最初:i = 10(第一个循环)

           j = 0 < 10(i) so it will loop from 0 to 9 times

现在嵌套循环结束后

i /= 2

i = 5 的 SO 值(第一次循环)2 次迭代。

这一次 j 将从 j = 0

i 的每个时间值将除以 2,类似地,j 的相应值将从 0 迭代到 i/2 次。

所以,T(n) = O(n + n/2 + n/4 + … 1) = O(n) for j(这仅用于 j 的迭代)

i               j

10           0-9 times

5              0 - 4 times

2             0 - 1 times

类似地,最初为 n 的 j 的值,即 10 在 n/2 形成 GP 时按顺序减少,因此我们得到 O(n)

【讨论】:

  • @Amit Nandal 现在你能解决你的问题了吗??
  • 我的理解是j迭代的时间复杂度是O(n),i迭代的时间复杂度是O(log n)。因此,这段代码的整体时间复杂度是O( nl*og(n)).我正确与否???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2015-06-17
  • 2017-09-11
  • 2015-06-12
  • 2021-02-25
相关资源
最近更新 更多