[英]Algorithm Analysis, Time Complexity of algorithm
m=1;
for(i=1;i<=n;i++){
m=m*2;
for(j=1;j<=m;j++){
do something that is O(1)
}
}
What will be time complexity of the above code ?? 上面代码的时间复杂度是多少? Please tell me how to solve these types of problem.
请告诉我如何解决这些类型的问题。
I prefer to look at these problems from the inside out. 我更喜欢从内到外看这些问题。 Removing the
m
, we have: 删除
m
,我们有:
for(i=1;i<=n;i++){
for(j=1;j<=2^i;j++){
do something that is O(1)
}
}
Or: 要么:
for(i=1;i<=n;i++){
O(2^i)
}
So overall: sum_1^n O(2^i)=O(2^(n+1))=O(2^n)
. 总体而言:
sum_1^n O(2^i)=O(2^(n+1))=O(2^n)
。
Inner loop will iterate 1 time, then 2 times, then ..., then 2^n times. 内循环将迭代1次,然后2次,然后......,然后2 ^ n次。 So we have
1 + 2 + 4 + ... + 2^n = 2^(n + 1) - 1 = O(2^n)
iterations of inner loop. 所以我们有
1 + 2 + 4 + ... + 2^n = 2^(n + 1) - 1 = O(2^n)
内部循环的1 + 2 + 4 + ... + 2^n = 2^(n + 1) - 1 = O(2^n)
次迭代。
One iteration of inner loop has constant complexity, so summed_inner_loop_complexity = O(2^n)
. 内循环的一次迭代具有恒定的复杂度,因此
summed_inner_loop_complexity = O(2^n)
。
Whole complexity is O(2^n)
. 整体复杂度为
O(2^n)
。
Formally and methodically, you can use Sigma notation: 从形式上和方法上,您可以使用Sigma表示法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.