【leetcode】974. Subarray Sums Divisible by K

题目如下:

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. 1 <= A.length <= 30000
  2. -10000 <= A[i] <= 10000
  3. 2 <= K <= 10000

解题思路:本题需要用到一个数学规律,如果a%c = b%c,那么(a-b)%c=0。我的解法就是从后往前遍历数组,依次累加每个元素的值并记为sum,同时用字典保存sum%K作为key值出现的次数。同时每累加一个元素,只要去字典中查找历史sum%K出现的次数,这个次数就是从以这个元素作为起点满足条件的子数组的个数。特别注意的是,如果sum%K=0,那么表示这个元素本身就满足条件,次数要+1。

代码如下:

class Solution(object):
    def subarraysDivByK(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        dic = {}
        count = 0
        res = 0
        for i in A[::-1]:
            count += i
            if count%K in dic:
                res += dic[count%K]
            if count % K == 0:
                res += 1
            dic[count%K] = dic.setdefault(count%K,0)+1
        return res
        

猜你喜欢

转载自www.cnblogs.com/seyjs/p/10317990.html