1. 程式人生 > >【leetcode】974. Subarray Sums Divisible by K

【leetcode】974. Subarray Sums Divisible by K

object tput inpu list ive 註意 遍歷數組 etc ==

題目如下:

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

【leetcode】974. Subarray Sums Divisible by K