-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
题目
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例
示例 1:
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
解题
解题方法
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var subarraySum = function(nums, k) {
let presumK = 0,
count = 0
const map = new Map()
map.set(0, 1)
for (let i = 0; i < nums.length; i++) {
presumK += nums[i]
if (map.has(presumK - k)) count += map.get(presumK - k)
map.set(presumK, (map.get(presumK) || 0) + 1)
}
return count
};