[英]What is the run-time complexity of this Code?
What is the run-time complexity of this Code? 该代码的运行时复杂度是多少?
#include <cstdio>
#include <cstring>
int main()
{
int n, i, l, j, c, ans = 25;
scanf("%d", &n);
char x[21], y[21];
scanf("%s", &x);
l = strlen(x);
for(i=1; i<n; i++)
{
scanf("%s", &y);
c = 0;
for(j=0 ;j<l; j++)
if(x[j] == y[j])
c++;
else
break;
strcpy(x, y);
if(ans > c)
ans = c;
}
printf("%d", ans);
return 0;
}
My lecturer tells me that the complexity of this code is O(n*n)
but I'm not convince with this answer cause the inner loop runs string length times. 我的讲师告诉我,此代码的复杂度为O(n*n)
但我不相信此答案会导致内部循环运行字符串长度时间。
The runtime of main()
is composed of the runtime of some constant-time statements and the runtime of the i
-loop: main()
的运行时由一些恒定时间语句的运行时和i
-loop的运行时组成:
T_main(n, l) ∈ O(1) + T_fori(n, l)
The i
-loop runs exactly (n - 1)
times and is composed of some constant-time statements and the runtime of the j
-loop: i
循环正好运行(n - 1)
次,并且由一些恒定时间语句和j
循环的运行时组成:
T_fori(n, l) ∈ (n - 1) * (O(1) + T_forj(n, l))
The runtime of the j-loop depends on the data. j循环的运行时间取决于数据。 In the best case, the first character of x
and y
are different, thus: 在最佳情况下, x
和y
的第一个字符不同,因此:
T_forj_best(n, l) ∈ 1 * O(1)
In the worst case, x
and y
have l
equal first characters, thus: 在最坏的情况下, x
和y
具有等于y
l
个字符,因此:
T_forj_worst(n, l) ∈ l * O(1) = O(l)
This yields: 这样产生:
T_fori_best(n, l) ∈ (n - 1) * (O(1) + O(1)) = O(n)
T_fori_worst(n, l) ∈ (n - 1) * (O(1) + O(l)) = O(n * l)
and 和
T_main_best(n, l) ∈ O(1) + O(n) = O(n)
T_main_worst(n, l) ∈ O(1) + O(n * l) = O(n * l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.