LeetCode 974. Subarray Sums Divisible by K--Python解法--数学题--取模求余

LeetCode 974. Subarray Sums Divisible by K–Python解法–数学题–取模求余


LeetCode题解专栏:LeetCode题解
LeetCode 所有题目总结:LeetCode 所有题目总结
大部分题目C++,Python,Java的解法都有。


题目地址:Subarray Sums Divisible by K - LeetCode


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

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


这道题目最容易想到穷举的方法,肯定会超时。
Python解法如下:

class Solution:
    def subarraysDivByK(self, A: List[int], K: int) -> int:
        length = len(A)
        count = 0
        for i in range(0, length):
            for j in range(i, length):
                if sum(A[i:j+1]) % K == 0:
                    count += 1
        return count

进行少量优化后还是超时:

class Solution:
    def subarraysDivByK(self, A: List[int], K: int) -> int:
        length = len(A)
        count = 0
        for i in range(0, length):
            now = 0
            for j in range(i, length):
                now += A[j]
                if now % K == 0:
                    count += 1
        return count

但是用动态规划不能解决。

最后看了解法后发现是数学题,无语了。

详细解法参考:Count all sub-arrays having sum divisible by k - GeeksforGeeks

class Solution:
    def subarraysDivByK(self, A: List[int], K: int) -> int:
        length = len(A)
        # create auxiliary hash
        # array to count frequency
        # of remainders
        mod = [0]*K
        # Traverse original array
        # and compute cumulative
        # sum take remainder of this
        # current cumulative
        # sum and increase count by
        # 1 for this remainder
        # in mod[] array
        cumSum = 0
        for i in range(length):
            cumSum = cumSum + A[i]

            # as the sum can be negative,
            # taking modulo twice
            mod[cumSum % K] = mod[cumSum % K] + 1

        result = 0  # Initialize result

        # Traverse mod[]
        for i in range(K):

            # If there are more than
            # one prefix subarrays
            # with a particular mod value.
            if mod[i] > 1:
                result = result + (mod[i]*(mod[i]-1))//2

        # add the elements which
        # are divisible by k itself
        # i.e., the elements whose sum = 0
        return result + mod[0]

你可能感兴趣的:(LeetCode,python-做题)