Leetcode 974. Subarray Sums Divisible by K

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 974. Subarray Sums Divisible by K相关的知识,希望对你有一定的参考价值。

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

1. Description

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 974. Subarray Sums Divisible by K

LC 974. Subarray Sums Divisible by K

974. Subarray Sums Divisible by K. 前缀和同余定理

974. Subarray Sums Divisible by K. 前缀和同余定理

LeetCode - 581. Shortest Unsorted Continuous Subarray

LeetCode 581. Shortest Unsorted Continuous Subarray (最短无序连续子数组)