其他分享
首页 > 其他分享> > leetcode 974 Subarray Sums Divisible by K

leetcode 974 Subarray Sums Divisible by K

作者:互联网

leetcode 974 Subarray Sums Divisible by K

1.题目描述

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

2.解题思路

先进行前缀和转换,然后将前缀和数列再转换为余数数列。该数列中重复的即可构成余数为零的子字符串。计算个数即可。

3.Python代码

class Solution:
    def subarraysDivByK(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        P,res=[0],0
        for x in A:
            P.append((P[-1]+x)%K)
        count = collections.Counter(P)
        for v in count.values():
            res=res+int(v*(v-1)/2)
        return res

标签:974,数列,Divisible,res,int,数组,Subarray
来源: https://blog.csdn.net/GQxxxxxl/article/details/86496863