- 常见的问题,思考的时候 创建的长度为 length+1
- 同时也可以边扫描边处理数据 560. 和为K的子数组
需要注意 hashmap 初始化的时候 {0:1}
class Solution:def subarraySum(self, nums: List[int], k: int) -> int:length=len(nums)sumValue,count=0,0hashmap={0:1}for num in nums:sumValue+=numif sumValue-k in hashmap:count+=hashmap[sumValue-k]if sumValue in hashmap:hashmap[sumValue]+=1else:hashmap[sumValue]:hashmap[sumValue]=1return count
如果不在意顺序,可以使用hashmap来存储数据 - Leetcode974
class Solution:def subarraysDivByK(self, A: List[int], K: int) -> int:hashmap={0:1}length=len(A)preSum=0count=0for i in range(length):preSum=(preSum+A[i])%Kcount+=hashmap.setdefault(preSum,0)if preSum in hashmap:hashmap[preSum]+=1else:hashmap[preSum]=1return count
