题目描述
给一个连续正整数组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)