Description
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Solution
1.build累积数组和
2.遍历,过程中 先check sum in dict, then add value for dict (这样可以去重复
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
cnt = 0
if len(nums)==0:
return cnt
max = [nums[0]]
for i in range(1,len(nums)):
max.append(nums[i]+max[-1])
d = {0:1} #相当于从开始1st ele的sum满足K的sum
for i in range(len(nums)):
if max[i]-k in d:
cnt += d[max[i]-k]
if max[i] in d:
d[max[i]]+=1
else:
d[max[i]]=1
return cnt
网友评论