Leetcode 560. Subarray Sum Equals K

Posted 周洋的Blog

tags:

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

前缀和(prefix sum/cumulative sum)

import collections


class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if not nums:
            return 0

        preSum, ret, size = [0], 0, len(nums)
        count = collections.Counter(preSum)
        if size == 1:
            return 1 if nums[0] == k else 0
        for val in nums:
            s = preSum[-1] + val
            preSum.append(s)
            ret += count.get(s - k, 0)
            count[s] = count.get(s, 0) + 1

        return ret

 

以上是关于Leetcode 560. Subarray Sum Equals K的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 560. Subarray Sum Equals K

[leetcode]Map-560. Subarray Sum Equals K

[LeetCode] 560. Subarray Sum Equals K_Medium

[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum

LeetCode 560. Subarray Sum Equals K (子数组之和等于K)

leetcode560. Subarray Sum Equals K