974.Subarray Sums Divisible by K(和可被 K 整除的子数组)

Description

Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.


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

题目链接:https://leetcode.com/problems/subarray-sums-divisible-by-k/

Difficulty: medium

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

分析

  • updating(Solution)

参考代码

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())
-------------本文结束你这么美,还坚持读完了-------------