美文网首页
Leetcode 974. Subarray Sums Divi

Leetcode 974. Subarray Sums Divi

作者: SnailTyan | 来源:发表于2021-09-03 15:45 被阅读0次

    文章作者: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 Divi

          本文链接:https://www.haomeiwen.com/subject/bxzbvltx.html