LeetCode---560. Subarray Sum Equals K

题目

给出一个整数数组和目标值,你需要找到所有的连续子序列,该子序列的和为目标值。输出满足该条件的子序列的个数。

Python题解

class Solution:
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        counts = {0: 1}
        sum_num = 0
        cnt = 0
        for n in nums:
            sum_num += n
            another_val = sum_num - k
            if another_val in counts:
                cnt += counts.get(another_val)
            counts[sum_num] = counts.get(sum_num, 0) + 1
        return cnt

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80496548