1. 程式人生 > >LeetCode---560. Subarray Sum Equals K

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