Subarray Sum Equals K

Subarray Sum Equals K

dict version - 72ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def subarraySum(self, nums, target):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dic = {0:1}
res = pre_sum = 0
for num in nums:
pre_sum += num
res += dic.get(pre_sum - target, 0)
dic[pre_sum] = dic.get(pre_sum, 0) + 1
return res

test code

1
2
In [112]: s = Solution(); t = s.subarraySum([1,1,1], 2); print(t)
2

leet code