用 JavaScript 在二進位制陣列中查詢連續 1 的最大數量


我們需要編寫一個 JavaScript 函式,該函式以二進位制陣列(僅包含 0 或 1 的陣列)作為唯一引數。

該函式應找到僅由 1 組成的陣列連續子陣列的長度並返回它。

例如 −

如果輸入陣列是 −

const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];

則輸出應為 −

const output = 4;

我們將使用滑動視窗演算法來捕獲僅由 1 組成的最大視窗(尺寸最大)。

示例

程式碼如下 −

 演示

const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
const findMaxConsecutiveOnes = (arr = []) => {
   let left = 0;
   let right = 0;
   let max = 0;
   while (right < arr.length) {
      if (arr[right] === 0) {
         if (right - left > max) {
            max = right - left
         };
         right++;
         left = right;
      } else {
         right++
      };
   };
   return right - left > max ? right - left : max;
}
console.log(findMaxConsecutiveOnes(arr));

輸出

控制檯中的輸出為 −

4

更新於:2021 年 2 月 26 日

297 次瀏覽

啟動你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.