用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP