# LeetCode-974. Subarray Sums Divisible by K

## LeetCode-974. Subarray Sums Divisible by K

Posted by Jae on October 14, 2019

### 1、题目

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


### 2、思路

1). 我们首先计算sum(0, a)存到数组中得 P=[0, 4, 9, 9, 7, 4, 5]

2). 然后按照同余关系进行计数得:

与0同余的有(0, 5) => (P[0], P[6])



3).对于同余的P[i]中，两两组合所得到的组合数相加就是要求的结果

### 3 实现

public class Solution {
public int subarraysDivByK(int[] A, int K) {
int n = A.length;
int[] P = new int[n+1];
for (int i = 0; i < n; i++){
P[i+1] = P[i] + A[i];
}

int[] C = new int[K];
for (int x : P){
C[(x % K + K) % K]++;
}

int ans = 0;
for (int c : C){
ans += c * (c-1) / 2;
}
return ans;
}
}


< script src = " / js / bootstrap.min.js " >