JavaScript 中至少包含两个元素的子阵和
问题
我们需要编写一个 JavaScript 函数,其中第一个参数是包含整数的数组 arr,第二个参数是单个整数 target。我们的函数应检查是否存在大小至少为 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP