2011-04-18 86 views
2

有人能告訴我以下代碼的時間複雜度嗎?下面代碼的時間複雜度?

#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

如果你告訴我們什麼讓你懷疑它是O(N),我們可以幫助你更好地理解。 – 2011-04-18 14:32:24

+1

Nitpick:什麼是n,你的輸入大小是多少?正如所寫的,代碼不會接受任何輸入並在恆定時間內運行。 「Duh,字符串長度」並不是一個完整的答案,因爲它看起來像行爲依賴於字符串中的空格,而這又是輸入的另一個參數。 – 2011-04-18 14:38:51

+0

@Cristopher:複雜性將取決於字符串的大小。 我認爲這裏的正確問題是這裏最好的,平均的和最差的時間複雜度。 – Elalfer 2011-04-18 14:46:56

回答

8

該算法可在僞代碼summarrized爲:

  1. 標記當前位置
  2. 直到空間被發現或結束在時間上向後移動一個字符去輸入達到
  3. 現在前進複製每個字符輸出,然後回到1,除非達到

EOI所以輸入被逆向工程&走過一次se,再前進一次,但在步驟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)既實現(在時間和空間,如果我們假設coutchar插入運營商O(1)),因爲O(n)算法的加入固定數量(此處爲兩個)還是O(n)(常數被忽略)。

+0

第一個解決方案,通知我不會改變一個常數值。 +1 – amit 2011-04-18 14:46:35

+0

*解釋*並且不會跳入「one loop = O(N)」謬誤的第一個解決方案。 +1 – 2011-04-18 14:49:34

+0

謝謝,回答這一問題。我很困惑,循環變量遞增的這種情況以及遍歷輸入時的遞減是否可以被稱爲O(n)。你的解釋有幫助。謝謝 :-) – NirmalGeo 2011-04-18 21:13:52

-2

「{對於(I = strlen的(A)-1; I> = 0; I = I +計數)}」

只有一個代碼中的循環和它的索引i被線性變化。 所以它爲O(n)

+0

「一個循環= O(N)」的謬誤。 '我'不會線性變化。 – 2011-04-18 14:42:48

+0

我正在更新只在聲明我+ =計數。 – shrishkrish 2011-04-18 14:50:12

+0

int i = 1; int n = 1000;而(i <= n)i * = 2;複雜度O(LGN),因爲這裏while循環的索引不是線性變化的。我說上面的代碼同樣的東西,我沒有得到-1的原因:( – shrishkrish 2011-04-18 14:54:06