给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
#前缀和
dic = {0:1}
presum = 0
count = 0
for i in nums:
presum += i
count += dic.get(presum-k, 0)
if presum in dic:
dic[presum] += 1
else:
dic[presum] = 1
return count