给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。

    示例:

    1. 输入:A = [4,5,0,-2,-3,1], K = 5
    2. 输出:7
    3. 解释:
    4. 7 个子数组满足其元素之和可被 K = 5 整除:
    5. [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]


    提示:

    1. 1 <= A.length <= 30000
    2. -10000 <= A[i] <= 10000
    3. 2 <= K <= 10000

      1. class Solution {
      2. public:
      3. int subarraysDivByK(vector<int>& A, int K) {
      4. int sum =0;
      5. unordered_map<int, int> hashMap{{0,1}};
      6. int res = 0;
      7. for(int i = 0;i<A.size();i++){
      8. sum += A[i];
      9. // 注意 C++ 取模的特殊性,当被除数为负数时取模结果为负数,需要纠正
      10. sum = (sum%K + K) %K;
      11. // cout<<sum<<endl;
      12. if(hashMap.count(sum)){
      13. res += hashMap[sum];
      14. }
      15. hashMap[sum]++;
      16. cout<<res<<endl;
      17. }
      18. return res;
      19. }
      20. };