在 C++ 中查詢需要替換為 1 的索引 0,以在二進位制陣列中獲得最長的連續 1 序列


假設我們有一個包含 N 個元素的陣列。這些元素要麼是 0 要麼是 1。找到需要替換為 1 的 0 的位置,以獲得最長的連續 1 序列。假設陣列類似於 arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1],輸出索引為 9。在索引 9 處將 0 替換為 1 會導致最長的連續 1 序列。

我們必須跟蹤三個索引:當前索引 (curr)、前一個零索引 (pz) 和前前一個零索引 (ppz)。現在遍歷陣列,當陣列元素為 0 時,計算 curr 和 ppz 之間的差值。如果差值大於最大值,則更新最大值,最後返回具有最大差值的 prev_zero 的索引。

示例

 即時演示

#include<iostream>
using namespace std;
int findIndex(bool arr[], int n) {
   int count_max = 0;
   int index;
   int pz = -1;
   int ppz = -1;
   for (int curr=0; curr<n; curr++) {
      if (arr[curr] == 0) {
         if (curr - ppz > count_max){
            count_max = curr - ppz;
            index = pz;
         }
         ppz = pz;
         pz = curr;
      }
   }
   if (n-ppz > count_max)
      index = pz;
   return index;
}
int main() {
   bool arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Index of 0 to be replaced is "<< findIndex(arr, n);
}

輸出

Index of 0 to be replaced is 9

更新於: 2019 年 12 月 18 日

178 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.