当前位置: 代码迷 >> 综合 >> Leetcode 974. Subarray Sums Divisible by K
  详细解决方案

Leetcode 974. Subarray Sums Divisible by K

热度:13   发布时间:2023-12-12 20:55:49.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 = 0stat = collections.defaultdict(int)stat[0] = 1total = 0for i in range(n):total += nums[i]remainder = total % kcount += stat[remainder]stat[remainder] += 1return count

Reference

  1. https://leetcode.com/problems/subarray-sums-divisible-by-k/