[leetcode 560]Subarray Sum Equals K

来源:互联网 发布:医疗网络营销策划 编辑:程序博客网 时间:2024/05/16 07:41

题目:求连续子集和为k的个数

代码出自:https://discuss.leetcode.com/topic/88041/super-simple-python

class Solution(object):

    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        sums = {0:1} # prefix sum array
        res = s = 0
        for n in nums:
            s += n # increment current sum
            res += sums.get(s - k, 0) # check if there is a prefix subarray we can take out to reach k
            sums[s] = sums.get(s, 0) + 1 # add current sum to sum count
        return res