JavaScript 中具有所需和的二进制子数组


问题

我们需要编写一个 JavaScript 函数,该函数将二进制数组 arr 作为第一个参数,将数字 target 作为第二个参数。

我们的函数应该对数组 arr 中存在的子数组的数量进行计数,其元素的总和等于 count。我们应该最终返回这个 count。

例如,如果函数的输入是

输入

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

输出

const output = 4;

输出说明

因为所需的子数组是

[1,0,1][1,0,1,0]
[0,1,0,1]
[1,0,1]

示例

 实时演示

const arr = [1, 0, 1, 0, 1];
const target = 2;
const countSubarrays = (arr = [], target = 1) => {
   const map = {}
   let sum = 0
   let count = 0
   for (const num of arr) {
      map[sum] = (map[sum] || 0) + 1
      sum += num
      count += map[sum - target] || 0
   }
   return count
};
console.log(countSubarrays(arr, target));

输出

4

更新于: 2021-04-23

64 次浏览

启动您的职业

通过完成课程获得认证

开始
广告
© . All rights reserved.