leetcode974. Subarray Sums Divisible by K
Posted seyjs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode974. Subarray Sums Divisible by K相关的知识,希望对你有一定的参考价值。
题目如下:
Given an array
A
of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible byK
.
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
解题思路:本题需要用到一个数学规律,如果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
以上是关于leetcode974. Subarray Sums Divisible by K的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 974. Subarray Sums Divisible by K
#Leetcode# 209. Minimum Size Subarray Sum
Minimum Size Subarray Sum -- leetcode
LeetCode -- Minimum Size Subarray Sum
[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum