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
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/

你可能感兴趣的:(Leetcode 974. Subarray Sums Divisible by K)