-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path560.py
29 lines (26 loc) · 829 Bytes
/
560.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#==================================================
#==> Title: subarray-sum-equals-k
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/12/2021
#==================================================
"""
https://leetcode-cn.com/problems/subarray-sum-equals-k/
"""
class Solution:
def subarraySum(self, nums, k):
HashMap = {0:1}
sum_, cnt = 0, 0
for x in nums:
sum_ += x
temp = HashMap.get(sum_ - k)
if temp is not None:
cnt += temp
HashMap[sum_] = HashMap.get(sum_) + 1 if HashMap.get(sum_) is not None else 1
return cnt
nums = [3, 4, 7, 2, -3, 1, 4, 2]
nums = [3, 4, 7, -7]
k = 7
mat = Solution()
mat.subarraySum(nums, k)