# 题目描述

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
``````

# 代码

## 半暴力解法（超时）

``````public int subarraysDivByK(int[] A, int K) {
int[] sum = new int[A.length];
for (int i = 0; i < A.length; i++) {
sum[i] = (i == 0 ? 0 : sum[i - 1]) + A[i];
}

int ans = 0;
if (sum[0] % K == 0) ans++;

for (int i = 1; i < sum.length; i++) {
if (sum[i] % K == 0) ans++;
for (int j = i - 1; j >= 0; j--) {
int tmp = sum[i] - sum[j];
if (tmp % K == 0) {
ans++;
}
}
}
return ans;
}
``````

## AC解法

``````sum[i]=p*K+ri
sum[j]=q*K+rj
``````

``````sum[j]-sum[i]=(q-p)*K+rj-ri
``````

``````public int subarraysDivByK(int[] A, int K) {
int mod[] = new int[K];

int cumSum = 0;
for (int i = 0; i < A.length; i++) {
cumSum += A[i];
// countSum % K 可能是负数，需要 +K
mod[((cumSum % K) + K) % K]++;
}

int ans = 0;
for (int i = 0; i < K; i++) {
if (mod[i] > 1) {
ans += (mod[i] * (mod[i] - 1)) / 2;
}
}

ans += mod[0];
return ans;
}
``````

### 推荐阅读更多精彩内容

• “谣言止于智者”，请允许我用此话作为开篇，的确是，谣言止于智者，这是真理！可是，何为谣言，何为智者？！这两天钱宝网...
赵老A阅读 105评论 0 1
• 关于旅游，一直是我身体力行的一件事，从我上大学起，每逢有假期我都会出去蹦哒，这几年不多不少，我也蹦哒了几个地方，一...
ShinyJR阅读 47评论 0 0
• 刚才看到一篇简文，顿时来了兴趣。原来照片还可以这样玩，哈哈，模仿下他。 这张不错吧？飘落的是杨树叶子，我们这边可多...
SinNOSG阅读 248评论 2 7
• 一般高额意外险 http://m.kbao123.com:80/2.2.0/share/product?userId
丰都吴红秀阅读 60评论 0 0