法1:超出时间限制
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
res=0
for left in range(len(nums)):
right=len(nums)-1
while right>=left:
if sum(nums[left:right+1])==k:
res+=1
right-=1
return res
法二:有点迷茫
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
res=0
pre_sum=0
pre_sums=defaultdict(int)
pre_sums[0]=1
for num in nums:
pre_sum+=num
res+=pre_sums[pre_sum-k]
pre_sums[pre_sum]+=1
return res