leetcode: Subarray Sums Divisible by K

Problem

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]

Solution

使用prefix sums的方法。
用一个presum变量记录当前位置 i 的总和 A [ 0 ] + . . . + A [ i ] A[0]+...+A[i] A[0]+...+A[i],取 k e y = p r e s u m % K key=presum\%K key=presum%K
那么对于任意 i 和 ( A [ 0 ] + . . . + A [ i ] ) % K = = k e y (A[0]+...+A[i])\%K==key (A[0]+...+A[i])%K==key,若存在 j<i 有 ( A [ 0 ] + . . . + A [ j ] ) % K = = k e y (A[0]+...+A[j])\%K==key (A[0]+...+A[j])%K==key,则等价于 ( A [ j + 1 ] + . . . + A [ i ] ) % K = = 0 (A[j+1]+...+A[i])\%K==0 (A[j+1]+...+A[i])%K==0。所以用一个hashmap来记录 p r e s u m % K = k e y presum\%K=key presum%K=key的个数。
特别的, ( A [ 0 ] + . . . + A [ i ] ) % K = = ( ( A [ 0 ] + A [ i − 1 ] ) % K + A [ i ] ) % K (A[0]+...+A[i])\%K == ((A[0]+A[i-1])\%K+A[i])\%K (A[0]+...+A[i])%K==((A[0]+A[i1])%K+A[i])%K

class Solution:
    def subarraysDivByK(self, A: 'List[int]', K: 'int') -> 'int':
        res = 0
        hashmap = {0:1}
        presum = 0
        for a in A:
            presum = (presum+a)%K
            
            if presum in hashmap.keys():
                res += hashmap[presum]
                hashmap[presum] += 1
            else:
                hashmap[presum] = 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值