简体   繁体   English

嵌套循环的大O复杂度

[英]Big O Complexity for nested loop

for (i = 0; i < 2*n; i += 2) 
{
  for (j=n; j > i; j--)
    //some code that yields O(1)
}

I thought the above would yield n*log(n) but I've seen another source say that it is really is n^2 complexity for big Oh. 我以为上面的代码会产生n*log(n)但是我看到另一个消息来源说,对于大哦,这确实是n^2复杂性。 Please explain to me which it is and how i could approach problems like this in the future. 请向我解释这是什么,以及将来如何解决此类问题。

You have a loop that depends on n and inside that loop you have another loop that also depends on n , thus the resulting O is O(n*n) ie O(n^2) . 您有一个依赖于n的循环,并且在该循环内有另一个也依赖于n循环,因此,结果O为O(n*n)O(n^2)

Big O only provides an upper bound on the growth rate of an algorithm. Big O仅提供算法增长率上限 Thus all constant factors are discarded. 因此,所有恒定因子均被丢弃。

Since Big O is for Upper Bound, so N * N will always be <= N^2, resulting in O(N*2). 由于Big O用于上限,因此N * N将始终<= N ^ 2,从而得出O(N * 2)。 Answer is right 答案是正确的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM