给你一个整数数组
nums和一个整数k,请你统计并返回 该数组中和为k的子数组的个数。子数组是数组中元素的连续非空序列。
题目要求连续非空序列,所以这里不能排序,可以使用前缀和 + 哈希表,从前缀和中查找cur_profix - k出现的次数直接相加,最终得到个数。
python
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
if not nums:
return 0
profix_dic = defaultdict(int)
profix_dic[0] = 1
cur_profix = 0
res = 0
for num in nums:
cur_profix += num
if cur_profix - k in profix_dic:
res += profix_dic[cur_profix - k]
profix_dic[cur_profix] += 1
return res