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]
分析
- prefix Sum是这类题目的基本技巧
- prefix Sum之后O(n^2)的暴力枚举,过不了case
- Time Limit Exceeded解法:
public int subarraysDivByK(int[] A, int K) {
int res = 0;
int len = A.length;
int[] sum = new int[len];
for(int i = 0; i < len; i++){
if (i == 0) sum[i] = A[i];
else sum[i] = sum[i - 1] + A[i];
}
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
int tmp;
if (i >= 1) tmp = sum[j] - sum[i - 1];
else tmp = sum[j];
if (tmp%K == 0) res++;
}
}
return res;
}
分析
- 注意到题目的特殊性,满足要求的**sub[i, j]**有如下特点:prefixSum[i’ - 1] % K == prefixSum[j’] % K ; i’ = i + 1, j’ = j + 1(0占位),周赛没有想到这一点
- 举例:Input: A = [4,5,0,-2,-3,1], K = 5
- prefixSum = [0, 4, 9, 9, 7, 4, 5] mod = [0, 4, 4, 4, 2, 4, 0] (首位0是占位作用)
- sub[0, 0] = prefixSum[1] - prefixSum[0];
- mod为4的索引有4个,[1,2,3,5],有6(1 + 2 + 3)subArray满足题目要求sub[1,2] sub[1,3] sub[1,5] sub[2,3] sub[2,4] sub[3,5]
- <mod, freq> 来记录相同mod的频率,从而计算结果
public int subarraysDivByK(int[] A, int K) {
// [4,5,0,-2,-3,1]
// [0,4,9,9,7,4,5]
// [0,4,4,4,2,4,0]
// <mod, freq>
HashMap<Integer, Integer> m = new HashMap<>();
m.put(0, 1);
int sumMode = 0;
int res = 0;
for (int a : A) {
sumMode = (sumMode + a) % K;
if (sumMode < 0) {
sumMode += K;
}
int freq = m.get(sumMode) == null ? 0 : m.get(sumMode);
res += freq;
m.put(sumMode, freq + 1);
}
return res;
}