解法一:
暴力解法循环直接判断从每个index开始的切片是否满足
class Solution:def subarraySum(self, nums: List[int], k: int) -> int:# 要求的连续子数组count = 0n = len(nums)for i in range(n):for j in range(i, n):if sum(nums[i:j+1]) == k:count += 1return count
超时了,对于求和这部分进行优化
class Solution:def subarraySum(self, nums: List[int], k: int) -> int:# 要求的连续子数组count = 0n = len(nums)for i in range(n):sum = 0for j in range(i, n):sum += nums[j]if sum == k:count += 1return count
依然超时,考虑其他方法
解法二:
哈希表+前缀和
class Solution:def subarraySum(self, nums: List[int], k: int) -> int:# 要求的连续子数组count = 0n = len(nums)preSums = collections.defaultdict(int)preSums[0] = 1presum = 0for i in range(n):presum += nums[i]# if preSums[presum - k] != 0:count += preSums[presum - k] # 利用defaultdict的特性,当presum-k不存在时,返回的是0。这样避免了判断preSums[presum] += 1 # 给前缀和为presum的个数加1return count