Subarray Sum Equals K(2sum and presum)
Input:
nums = [1,1,1], k = 2
Output:
2PrefixSum + Dictionary
> Time Complexity O(N)
> Space Complexity O(N)Last updated
Input:
nums = [1,1,1], k = 2
Output:
2PrefixSum + Dictionary
> Time Complexity O(N)
> Space Complexity O(N)Last updated
if we know SUM[0, i - 1] and SUM[0, j], then we can easily get SUM[i, j]. 因为不包含前数,所以Map[0]=1import collections
class Solution:
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return 0
ret = 0
n = len(nums)
map = collections.defaultdict(int)
map[0] = 1 #因为前面总是不包含,所以需要map[0]补足?
sum=0
for i in range(n):
sum+=nums[i]
if sum - k in map:
ret += map[sum- k]#+= 不是 =
map[sum] += 1 #+= 不是 =
return ret