c++ - 下面代码的时间复杂度?

标签 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;
} 

我真的很困惑这是否可以归类为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)(常量被忽略)。

关于c++ - 下面代码的时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5704411/

相关文章:

c++ - Boost.Signals 弃用

C++ WinINET FtpPutFile 错误代码 3

C++ 使用 RAII 和抛出的析构函数

c++ - 在 C++ 中进行简单算术运算时遇到问题

algorithm - 一条直线上最近的一对点

c++ - 为什么当我在整数左侧输入零时,c++ borland 编译器会更改整数值?

algorithm - 如何检查此算法是否可能不会终止?

algorithm - 图的团数

c++ - 以下函数的时间复杂度

dart - Dart 中 Map containsKey 和 containsValue 的时间复杂度