子数组总和包含JavaScript中的至少两个元素

问题

我们需要编写一个JavaScript函数,该函数将一个整数数组arr作为第一个参数,将一个整数目标作为第二个参数和第一个参数。我们的函数应检查是否存在大小不小于2的连续子数组,其总和为k的倍数,即,总和为n * k,其中n可以是任何整数。

如果存在,则返回true,否则返回false。

例如,如果函数的输入为-

const arr = [23, 2, 6, 4, 7];
const target = 6;

那么输出应该是-

const output = true;

输出说明:

因为[23、2、6、4、7]是大小为5的连续子数组,总和为42。

示例

为此的代码将是-

const arr = [23, 2, 6, 4, 7];
const target = 6;
const checkSubarraySum = (arr = [], target = 1) => {
   let sum = 0
   const hash = {}
   hash[0] = -1;
   for (let i = 0; i<arr.length; i++) {
      sum += arr[i]
      if (target!=0) sum %= target
      if ( hash[sum] !== undefined ) {
         if(i-hash[sum]>1) return true
      } else {
         hash[sum] = i
      }
   };
   return false;
};
console.log(checkSubarraySum(arr, target));
输出结果

控制台中的输出将是-

true