560. Subarray Sum Equals K

时间:2022-07-29 10:11:20

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
 class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sums = {0:1}
s = 0
cnt = 0
for i in nums:
s += i
if sums.get(s-k) != None:
cnt += sums[s-k]
if sums.get(s) == None:
sums[s] = 1
else:
sums[s] += 1
return cnt