JavaScript 中具有 0 和 1 的连续子数组
问题:
我们需要编写一个JavaScript函数,它接受一个二进制数组arr(一个只包含0或1的数组)。我们的函数应该从由相同数量的1和0组成的数组中返回连续子数组的长度。
例如,如果函数的输入是-
const arr = [1, 0, 0, 1, 0, 1, 0, 0];
那么输出应该是-
const output = 6;
输出说明
数组的前6个元素是1,0,0,1,0,1(三个1和三个0)
示例
此代码将是-
const arr = [1, 0, 0, 1, 0, 1, 0, 0]; const findMaxLength = (arr = []) => { const { length } = arr; if (length < 2){ return 0 }; const map = new Map(); map.set(0, -1); let sum = 0; let max = 0; for (var i = 0; i < length; i++) { sum += arr[i] === 0 ? -1 : 1; if (map.has(sum)) { max = Math.max(max, i - map.get(sum)); } else { map.set(sum, i); }; }; return max; }; console.log(findMaxLength(arr));
代码说明
这里,我们把0看作-1,1看作1,计算不同窗口的总和,当总和为0时,我们知道子数组必须有相同的0和1数。
输出结果
控制台中的输出将是-
6