这些依赖嵌套循环的时间复杂度是多少?

时间:2014-08-10 02:26:07

标签: algorithm big-o time-complexity

如何计算这些算法的时间和空间复杂度? 我引用了很多网站,但令我困惑。请任何人解释一下。

1

 for(i=0;i<n;i++)
 {
    for(j=i;j<n;j++)//this for loop is based on previous 'i'
    {
       foo();
    }
 }

2

while(m<n)
{
    for(i=0;i<n;i++)
    {
         foo();
    }
}

如果可能的话,请用更多的例子来解释我。感谢。

1 个答案:

答案 0 :(得分:1)

first part of the question ,  
i = 0, 1, 2, 3, 4, ... , n   
j = i = 0, 1, 2, 3, 4, ... n  

first time: i = 0  
inner loop will execute from 0 to n ( n times ) 

second time , i = 1  
j = 1, 2, 3, 4, .... , n ( n-1 times)  

third time : i = 2  
j = 2, 3, 4, ... , n

i = 0 : j = 0 -> n (n)  
i = 1 : j = 1 -> n (n-1)   
i = 2 : j = 2 -> n (n-2)   
i = n - 1 (i < n) : j = (n - 1) -> n ( 1)    

sum( 1 + 2 + 3 + 4 + ..... + n) = n*(n + 1)/2 = O(n^2)    
second part of the question m does not increment this loop will not  
stop.