974. 和可被 K 整除的子数组

给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。
示例:
输入:A = [4,5,0,-2,-3,1], K = 5 输出:7 解释: 有 7 个子数组满足其元素之和可被 K = 5 整除: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
提示:
  1. 1 <= A.length <= 30000
  1. 10000 <= A[i] <= 10000
  1. 2 <= K <= 10000

前缀和

思路
元素之和可被 K 整除的(连续、非空)子数组。
怎么判断可被k整除呢?
在数组的前缀和数组中, 若 sum_[i]%k ==n, sum_[j] % k == n 那么原数组从i到k之间的元素必然可被k整除,因为对余数没有贡献。
题解
class Solution: def subarraysDivByK(self, nums: List[int], k: int) -> int: count = 0 sum_ = 0 hashmap = collections.defaultdict(int) hashmap[0] = 1 for i in range(0, len(nums)): sum_ += nums[i] temp = sum_ % k count += hashmap[temp] hashmap[sum_%k] += 1 return count