标签:while bsp 去掉 复杂度 bubuko 技术 sum info 分析
分析一下这段代码的时间复杂度:
int cal(int n) {
int sum = 0;
int i = 1;
for (; i <= n; ++i) {
sum = sum + i;
}
return sum;
}
每一行代码的执行时间是 1 ,for 循环执行了n次。所以是2+n次,去掉常数就是O(n)
int cal(int n) {
int sum = 0;
int i = 1;
int j = 1;
for (; i <= n; ++i) {
j = 1;
for (; j <= n; ++j) {
sum = sum + i * j;
}
}
}
这段代码是俩个for循环。所以是O(n2)
int cal(int n) {
int sum_1 = 0;
int p = 1;
for (; p < 100; ++p) {
sum_1 = sum_1 + p;
}
int sum_2 = 0;
int q = 1;
for (; q < n; ++q) {
sum_2 = sum_2 + q;
}
int sum_3 = 0;
int i = 1;
int j = 1;
for (; i <= n; ++i) {
j = 1;
for (; j <= n; ++j) {
sum_3 = sum_3 + i * j;
}
}
return sum_1 + sum_2 + sum_3;
}
相加,复杂度是最大的那个
int cal(int n) {
int ret = 0;
int i = 1;
for (; i < n; ++i) {
ret = ret + f(i);
}
}
int f(int n) {
int sum = 0;
int i = 1;
for (; i < n; ++i) {
sum = sum + i;
}
return sum;
}
相乘的时间复杂度是O(n3)
i=1;
while (i <= n) {
i = i * 2;
}
i=1;
while (i <= n) {
i = i * 3;
}
时间复杂度是O(logn)
int cal(int m, int n) {
int sum_1 = 0;
int i = 1;
for (; i < m; ++i) {
sum_1 = sum_1 + i;
}
int sum_2 = 0;
int j = 1;
for (; j < n; ++j) {
sum_2 = sum_2 + j;
}
return sum_1 + sum_2;
}
时间复杂度是O(n)+O(n)
标签:while bsp 去掉 复杂度 bubuko 技术 sum info 分析
原文地址:https://www.cnblogs.com/hanguocai/p/9897683.html