Skip to content

Commit bcede51

Browse files
authored
Update 560-subarray-sum-equals-k.js
1 parent c8103af commit bcede51

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

560-subarray-sum-equals-k.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,26 @@ const subarraySum = function(nums, k) {
2121
}
2222
return totalNum
2323
}
24+
25+
// another
26+
27+
/**
28+
* @param {number[]} nums
29+
* @param {number} k
30+
* @return {number}
31+
*/
32+
const subarraySum = function (nums, k) {
33+
const n = nums.length, hash = { 0: 1 }
34+
let pre = 0
35+
if (nums.length === 1) {
36+
return nums[0] === k ? 1 : 0
37+
}
38+
let res = 0
39+
for (let i = 0; i < n; i++) {
40+
const cur = pre + nums[i]
41+
if (hash[cur - k] != null) res += hash[cur - k]
42+
hash[cur] = (hash[cur] || 0) + 1
43+
pre = cur
44+
}
45+
return res
46+
}

0 commit comments

Comments
 (0)