1. 程式人生 > >Leetcode 974. Subarray Sums Divisible by K

Leetcode 974. Subarray Sums Divisible by K

for class prefix sdi pan array count val col

前綴和(prefix sum/cumulative sum)的應用

class Solution(object):
    def subarraysDivByK(self, A, K):
        P = [0]
        for x in A:
            P.append((P[-1] + x) % K)

        count = collections.Counter(P)
        return sum(v*(v-1)/2 for v in count.values())

Leetcode 974. Subarray Sums Divisible by K