和为 K 的子数组-数组560-python

  • Post author:
  • Post category:python



前缀和算法:

可以O(1)时间下得到子数组的和。

在这里插入图片描述


python

class Solution:
    def subarraySum(self, nums: List[int], k: int):
        n = len(nums)
        preNum = [0] * (n+1)
        needs = {0:1}
        count = 0

        for i in range(n):
            preNum[i+1] = preNum[i] + nums[i]
        
        for i in range(1, n+1):
            target = preNum[i] - k

            if target in needs.keys():
                count += needs[target]

            if preNum[i] not in needs.keys():
                needs[preNum[i]] = 1
            else:
                needs[preNum[i]] += 1
        
        return count



版权声明:本文为VaccyZhu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。