-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
42 lines (41 loc) · 979 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
const checkSubarraySum = function (nums, k) {
if (nums.length < 2) {
return false;
}
k = Math.abs(k);
if (k === 1) {
return true;
}
let sumMap = new Map(), sum = 0;
sumMap.set(0, [-1]);
for (let i = 0; i < nums.length; ++i) {
sum += nums[i];
let indices = sumMap.get(sum);
if (!indices) {
sumMap.set(sum, [i]);
} else {
indices.push(i);
}
}
for (let s of sumMap.keys()) {
let target = s;
let idx = sumMap.get(s)[0];
while (target <= sum) {
let indices = sumMap.get(target);
if (indices && indices[indices.length - 1] - idx >= 2) {
return true;
}
if (k === 0) {
break;
}
target += k;
}
}
return false;
};
module.exports = checkSubarraySum;