我创建了一个简单的程序,现在我要寻找时间复杂度(big-O)。下面是代码:
'if' can either be 0 or 1, therefore assigned 'z'
1st 'for loop' is A
2nd 'for loop' is B
'if' inside the 2nd 'for loop' is B, since it will run n time depending on the 2nd for loop
3rd 'for loop' is B
4th 'for loop' is B, since it is nested for loop inside 3rd 'for loop'
'if' can either be 0 or 1, therefore assigned 'v'
5th 'for loop' is B
这是我尝试解决的问题:
z + A + B + B + (B x B) + v + B
= z + A + 3B + B^2 + v
= O(B^2)
因此:
{{1}}
当涉及嵌套循环时,我对如何计算时间复杂度感到困惑(我是算法新手)。我的方法部分正确,还是完全错误?对于这样一个简单的算法,我该如何解决这样的时间复杂性问题?
最后,如果上述嵌套的for循环之一变为“ while”循环,那么时间复杂度的计算又将如何?