给定一个整数数组 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 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000
前缀和 + 哈希表。
注意:不同的语言负数取模的值不一定相同,有的语言为负数,对于这种情况需要特殊处理。
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
ans = s = 0
counter = Counter({0: 1})
for num in nums:
s += num
ans += counter[s % k]
counter[s % k] += 1
return ans
class Solution {
public int subarraysDivByK(int[] nums, int k) {
Map<Integer, Integer> counter = new HashMap<>();
counter.put(0, 1);
int s = 0, ans = 0;
for (int num : nums) {
s += num;
int t = (s % k + k) % k;
ans += counter.getOrDefault(t, 0);
counter.put(t, counter.getOrDefault(t, 0) + 1);
}
return ans;
}
}
class Solution {
public:
int subarraysDivByK(vector<int>& nums, int k) {
unordered_map<int, int> counter;
counter[0] = 1;
int s = 0, ans = 0;
for (int& num : nums)
{
s += num;
int t = (s % k + k) % k;
ans += counter[t];
++counter[t];
}
return ans;
}
};
func subarraysDivByK(nums []int, k int) int {
counter := map[int]int{0: 1}
ans, s := 0, 0
for _, num := range nums {
s += num
t := (s%k + k) % k
ans += counter[t]
counter[t]++
}
return ans
}