Leetcode 974. Subarray Sums Divisible by K

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Subarray Sums Divisible by K

2. Solution

解析:Version 1,使用前缀和来解决,遍历数组,求前缀和,然后求余数,统计余数次数并保存到字典中,当碰到余数相同时,则意味着当前数组减去之前的前缀和数组可以被k整除,将次数加到count中,更新余数次数。注意,假设第一个数就可以整除k,此时数组中没有余数0的次数,因此stat[0]=1

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
n = len(nums)
count = 0
stat = collections.defaultdict(int)
stat[0] = 1
total = 0
for i in range(n):
total += nums[i]
remainder = total % k
count += stat[remainder]
stat[remainder] += 1
return count

Reference

  1. https://leetcode.com/problems/subarray-sums-divisible-by-k/
如果有收获,可以请我喝杯咖啡!