# 974.Subarray Sums Divisible By K

**974.Subarray Sums Divisible By K**

难度:Medium

> 给定一个整数数组 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
```

如果某个子列能整除，则从零开始到头尾的子列和模K相同，最后找出相同的模的组合。 模为0的时候的统计数应该+1，默认为索引0之前有一个模为0的起点。

```
class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        if(A.empty()) return 0;
        vector<int> allMod(K,0);
        int sum=0;
        allMod[0]=1;
        for(int i=0;i<A.size();i++)
        {
            sum+=A[i];
            sum %=K;
            if(sum<0) 
            {
                sum+=K;
            }
            allMod[sum]++;
         //cout<<sum<<endl;
        }
        int res=0;
        for(auto m:allMod)
        {
            if(m>1)
            res+=m*(m-1)/2;
        }

        return res;
    }
};
```

> 执行用时 :92 ms, 在所有 C++ 提交中击败了82.90%的用户\
> 内存消耗 :28.7 MB, 在所有 C++ 提交中击败了50.00%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/974.subarray_sums_divisible_by_k.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
