1. 常见的问题,思考的时候 创建的长度为 length+1
    2. 同时也可以边扫描边处理数据 560. 和为K的子数组

    需要注意 hashmap 初始化的时候 {0:1}

    1. class Solution:
    2. def subarraySum(self, nums: List[int], k: int) -> int:
    3. length=len(nums)
    4. sumValue,count=0,0
    5. hashmap={0:1}
    6. for num in nums:
    7. sumValue+=num
    8. if sumValue-k in hashmap:count+=hashmap[sumValue-k]
    9. if sumValue in hashmap:hashmap[sumValue]+=1
    10. else:hashmap[sumValue]:hashmap[sumValue]=1
    11. return count
    1. 如果不在意顺序,可以使用hashmap来存储数据 - Leetcode974

      1. class Solution:
      2. def subarraysDivByK(self, A: List[int], K: int) -> int:
      3. hashmap={0:1}
      4. length=len(A)
      5. preSum=0
      6. count=0
      7. for i in range(length):
      8. preSum=(preSum+A[i])%K
      9. count+=hashmap.setdefault(preSum,0)
      10. if preSum in hashmap:hashmap[preSum]+=1
      11. else:hashmap[preSum]=1
      12. return count