连续子串和被b整除

题目描述

给一个连续正整数组nums,求其中可以被k整除的子数组的个数。

示例

nums = [5, 2, 2]
b = 3

方法

哈希表优化

创建一个计数器dic,用来记录当前下标到i时的子串和total对k求余得到的数出现的次数。
如果当前子数组和total对k求余存在于dic中,则子数组个数count加上键对应的值。
然后将total对k求余的结果进行计数。

class Solution:
    def subarraySum(self, nums, k):
        dic = collections.Counter()
        count, total = 0, 0
        dic[total] = 1
        for i in range(len(nums)):
            total += nums[i]
            count += dic[total % k]
            dic[total % k] += 1
        return count
if __name__=='__main__':
    a = Solution().subarraySum([1, 2, 3, 4, 5], 3)
    print(a)

初始化计数器dic = {0:1}
当 i = 1时,total = 1,满足条件子串count = 0,满足条件子串:无,字典dic = {0:1,1:1};
当 i = 2时,total = 3,满足条件子串count = 1,满足条件子串:{[1, 2]},字典dic = {0:2,1:1};
当 i = 3时,total = 6,满足条件子串count = 3,满足条件子串:{[1, 2], [1,2,3], [3]},字典dic = {0:3,1:1};
当 i = 4时,total = 10,满足条件子串count = 4,满足条件子串:{[1, 2], [1,2,3], [3], [2, 3, 4]},字典dic = {0:3,1:2};
当 i = 5时,total = 15,满足条件子串count = 7,满足条件子串:{[1, 2], [1,2,3], [3], [2, 3, 4], [1, 2, 3, 4, 5], [3, 4, 5], [5]},字典dic = {0:4,1:2};

无包字典版

class Solution:
    def subarraySum(self, nums, k):
        dic = dict({0:1})
        count, total = 0, 0
        for i in range(len(nums)):
            total += nums[i]
            if total % k in dic.keys():
                count += dic[total % k]
                dic[total % k] = dic[total % k] + 1
            else:
                dic[total % k] = 1
        return count
if __name__=='__main__':
    a = Solution().subarraySum([1, 2, 3, 4, 5], 3)
    print(a)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值