560. 和为 K 的子数组(中等)-子串

2023-05-19  本文已影响0人  MatrixZ

给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的连续子数组的个数 。

分析

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        # 计算累计和
        # 边走边计算对应的sum_all -k 是否已经存在,并且需要用字典记录,而不是集合,因为前面有可能有多个相同的sum_all
        sum_to_count = {}
        # 重大陷阱,需要定义sum为0时值为1,因为有可能包含第一个元素,这样也需要有个被减数
        sum_to_count[0] = 1
        n = len(nums)
        sum_all = 0
        res = 0
        for n in nums:
            sum_all += n
            if sum_all - k in sum_to_count:
                res += sum_to_count[sum_all - k]
            
            if sum_all in sum_to_count:
                sum_to_count[sum_all] += 1
            else:
                sum_to_count[sum_all] = 1
        
        return res
上一篇 下一篇

猜你喜欢

热点阅读