Nir*_*Geo 2 c++ algorithm time-complexity
有人能告诉我下面代码的时间复杂度吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
我真的很困惑这是否可归类为O(n).请帮忙,提前谢谢.
该算法可以在伪代码中进行汇总,如下:
所以输入被反向穿过一次,一次向前,但没有回来先前读取的位置在任一步骤2.或3并从步骤3到1.它直接调整迭代器切换时.该count变量用于跟踪算法的状态(实际上它是一个简单的状态机).它也被重用来定义迭代的方向.
所以,算法实际上就是这样O(n).
为了更加清晰,可以在不改变复杂性的情况下将其重写为:
void printStringWithWordReversed(const char* a) {
int i,j,display_ToVal= strlen(a)-1, display_FromVal;
for( i=display_ToVal; i>=0 ; i=i+-1)
{
if ( (a[i] == ' ' || i == 0))
{
// When entering this branch, we are switching from state 2 to
// state 3 (this is the content of the first branch).
cout << " ";
display_FromVal = i;
if ( i == 0 )
cout << a[i];
// This loop correspond to the state 3, and is equivalent to the
// previous code in the particular case when count == 1.
for (j = display_FromVal+1; j <= display_ToVal; j=j+1)
{
cout << a[j];
}
// This postlude correspond to the transition from state 3 to state 1
// and correspond to the second branch in the original algorithm.
display_ToVal = display_FromVal - 1;
if ( i == 0 )
break;
continue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,我们从结尾开始查找每个单词,并以正确的顺序输出它们.这显然O(n)与两种实现(在时间和空间中,如果我们假设cout插入运算符为charis O(1)),因为添加固定数(此处为2)的O(n)算法仍然是O(n)(常量被忽略).