下面代码的时间复杂度
Time complexity of the code below?
谁能告诉我以下代码的时间复杂度?
#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。,除非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)
在时间和空间上的两种实现(如果我们假设char
的cout
插入算子是O(1)
),因为添加O(n)
算法的固定数(这里是两个)仍然是O(n)
(常数被忽略)。
"{for(i=strlen(a)-1;我> = 0;我=我+数)}"
在你的代码中只有一个for循环,它的索引i是线性变化的。这就是为什么是O(n)
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 函数的时间复杂度是多少?
- 计算两个代码块的时间复杂度
- 给定C++代码的时间复杂度是多少?
- 以下递归代码的时间复杂度是多少?
- 此特定代码的时间复杂度是多少?
- 谁能帮我降低以下代码的时间复杂度?
- 以下代码片段的时间复杂度是多少?
- 此代码段的时间复杂度
- 用于搜索的给定代码的时间复杂度是多少
- 如何降低以下代码块的时间复杂度
- 给定代码的时间复杂度
- 这个代码(来自leetcode)的时间复杂度是多少
- &&运算符的 C++ 代码时间复杂度
- 以下代码的时间复杂度是多少
- 什么是"渐近紧时间复杂度"?此代码的时间复杂度是否渐近紧张?
- 优化的c++代码,时间复杂度为O(n2),空间复杂度为0(1),用于后续输入
- 下面代码的时间复杂度