560. Subarray Sum Equals K (Medium) - TengnanYao/daily_leetcode GitHub Wiki
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums = [0] + nums
n = len(nums)
result = 0
for i in range(n - 1):
nums[i + 1] += nums[i]
h = {}
for i in range(n):
val = nums[i] - k
if val in h:
result += h[val]
h[nums[i]] = h.get(nums[i], 0) + 1
return result