下面代码的时间复杂度

Time complexity of the code below?

本文关键字:时间复杂度 代码      更新时间:2023-10-16

谁能告诉我以下代码的时间复杂度?

#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)。请帮忙,提前谢谢。

该算法可以用伪代码概括为:

  1. 标记当前位置
  2. 每次向后一个字符,直到找到空格或到达输入结束
  3. 现在向前复制每个字符到输出,然后返回1。,除非eoi达到

因此,输入将反向遍历一次,然后再向前遍历一次,但在步骤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;
        }       
    }
}

所以我们从末尾开始查找每个单词,并以正确的顺序输出它们。这显然是O(n)在时间和空间上的两种实现(如果我们假设charcout插入算子是O(1)),因为添加O(n)算法的固定数(这里是两个)仍然是O(n)(常数被忽略)。

"{for(i=strlen(a)-1;我> = 0;我=我+数)}"

在你的代码中只有一个for循环,它的索引i是线性变化的。这就是为什么是O(n)