2015-09-30 57 views
0

我想計算數組中最大的連續數。在下面,它返回給我4.看起來陣列中的所有trues都被加起來了。我的工作出了什麼問題?這是我的代碼。數組中的最大連續重複數

int main() 
{ 
int maxCount = 0; 
bool list[7]; 
list[0] = true; 
list[1] = true; 
list[2] = false; 
list[3] = false; 
list[4] = true; 
list[5] = true; 
list[6] = false; 

for (int i = 0; i < 6; i++) 
{ 
    int count = 0; 
    if (list[i]==true) 
    { 
     count++; 
     for (int j = i + 1; j < 7; j++) 
     { 
      if (list[j]== list[i]) 
      { 
       count++; 
      } 
     } 
    } 
    if (count > maxCount) 
    { 
     maxCount = count; 
    } 
} 
cout << maxCount << endl; 
} 
+2

你不需要O(n * n)算法。在O(n)中可以達到相同的效果。 此外,'list'是'std'命名空間中的一個內置容器。既然你使用'cout',它也是'std',你可以考慮重命名你的數組! – CinCout

回答

0

這是更好地再次考慮countmaxCount之間的關係。

int maxCount = 0; 
int count = 0; 
int size = sizeof(list)/sizeof(bool); 
for (int i = 0; i < size; i++) { 
    if (list[i]==true) { 
     count++; 
    } else { 
     if (count > maxCount) { 
      maxCount = count; 
     } 
     count = 0; 
    } 
} 
if (count > maxCount) { 
    maxCount = count; 
} 
cout << maxCount << endl; 
在真/假變化

LIVE

0

休息和小心的只有最後一個真正的

#include <iostream> 

int main() 
{ 
    using namespace std; 

    int maxCount = 0; 
    bool list[7]; 
    list[0] = true; 
    list[1] = true; 
    list[2] = false; 
    list[3] = false; 
    list[4] = true; 
    list[5] = true; 
    list[6] = false; 

    for (int i = 0; i < 7; i++) // be careful last true 
    { 
     int count = 0; 
     if (list[i]==true) 
     { 
      count++; 
      for (int j = i + 1; j < 7; j++) 
      { 
       if (list[j]== list[i]) 
       { 
        count++; 
       } 
       else 
       { 
        break; // true/false transition 
       } 
      } 
     } 
     if (count > maxCount) 
     { 
      maxCount = count; 
     } 
    } 
    cout << maxCount << endl; 
} 
1

要實現的方式是完全錯誤的。您將在陣列中添加所有true條目,而不會考慮中間的false

這樣做:

int currentCount = 0, maxCount = 0; 
for (int i = 0; i < 7; ++i) 
{ 
    // arr is the name of the array 
    if(arr[i]) ++currentCount; 
    else currentCount = 0; // resetting to zero if false encountered 
    maxCount = ((currentCount > maxCount) ? currentCount : maxCount); 
} 
cout << maxCount << endl; 
+1

三元可以用'maxCount = std :: max(maxCount,count);'代替。 – Jarod42

+0

是的,這也是可能的。 – CinCout

0

你應該遍歷數組只是一次,但使用計數器:

  • 首先對真正價值的當前連勝
  • 其次爲最高條紋

每次遇到一個false將當前的連勝計數器重置爲零,並且每次遇到true時,遞增當前連勝的值並檢查它是否高於連勝計數器,如果是,則更新它。

相關問題