题目链接:点击这里

 

public static int subarraysDivByK(int[] A, int K) {
        int ans = 0,sum = 0;
        int[] B = new int [K];
        for(int j=0;j<A.length;j++) {
            sum+=A[j];
            B[(sum%K+K)%K]++;
        }
        for(int j=0;j<K;j++) {
            if(B[j]>1) {
                ans+=(B[j]-1)*B[j]/2;
            }
        }
        ans+=B[0];
        return ans ;
    }

Runtime:  5 ms, faster than 94.00% of Java online submissions for Subarray Sums Divisible by K.
Memory Usage:  45.2 MB, less than 23.53% of Java online submissions forSubarray Sums Divisible by K.