难度: Medium
原题连接
内容描述
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Note:
1 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
一看就是前缀和,处理比较巧妙,两个index的前缀和相等说明中间那个区间都是K的倍数
class Solution:
def subarraysDivByK(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
prefix = [0]
for num in A:
prefix.append((prefix[-1] + num) % K)
count = collections.Counter(prefix)
return sum(v * (v-1) // 2 for v in count.values())