leetcode: Subarray Sums Divisible by K

本文介绍了一种高效算法,用于计算给定整数数组中,所有连续且非空子数组中元素之和能被K整除的子数组数量。通过使用前缀和与哈希映射,算法能在O(n)时间内解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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],取key=presum%Kkey=presum\%Kkey=presum%K
那么对于任意 i 和(A[0]+...+A[i])%K==key(A[0]+...+A[i])\%K==key(A[0]+...+A[i])%K==key,若存在 j<i 有(A[0]+...+A[j])%K==key(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来记录presum%K=keypresum\%K=keypresum%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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值