【发布时间】:2011-04-18 14:29:42
【问题描述】:
谁能告诉我以下代码的时间复杂度?
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char a[100]= "Gosh I am confused :D";
int i,count= -1,display_ToVal= strlen(a)-1, display_FromVal;
for( i=strlen(a)-1 ; i>=0 ; i=i+count)
{
if ( (a[i] == ' ' || i == 0) && count == -1)
{
cout << " ";
display_FromVal = i;
count = 1;
if ( i == 0 )
cout << a[i];
continue;
}
else if( count == 1 && i == display_ToVal)
{
cout << a[i];
display_ToVal = display_FromVal - 1;
i = display_FromVal;
count = -1;
if(display_FromVal == 0)
break;
else
continue;
}
else if (count == 1)
cout << a[i];
else
continue;
}
return 1;
}
我真的很困惑这是否可以归类为O(n)。请帮忙,提前谢谢。
【问题讨论】:
-
如果您告诉我们是什么让您怀疑它是 O(N),我们可以帮助您更好地理解。
-
Nitpick:n 是多少,您的输入大小?如所写,代码不接受任何输入并在恒定时间内运行。 “呃,字符串长度”并不是一个完整的答案,因为看起来行为取决于字符串中的空格,这是输入的另一个参数。
-
@Cristopher:复杂性无论如何都取决于字符串的大小。我认为这里的正确问题是这里最好、平均和最差情况的时间复杂度是多少。
-
我刚刚在这种情况下硬编码了 i/p,但 i/p 可以是任何东西。由于 I 的值是递增和递减的,所以我在是否可以将其视为 O(n) 的问题上进退两难。
标签: c++ algorithm time-complexity