Problem
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:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
Solution
我们用一个HashMap<preSum,count>来保存:和为preSum的subarray的数量。
通过遍历整个输入的nums数组,不断更新HashMap。
在遍历到时间 ttt 时,nums[0]+nums[1]+...+nums[t−1]=preSumnums[0]+nums[1]+...+nums[t-1] = preSumnums[0]+nums[1]+...+nums[t−1]=preSum,在这个时刻之前共有HashMap[V]HashMap[V]HashMap[V](V=presum−kV = presum-kV=presum−k)个indices jjj 使得nums[0]+nums[1]+...+nums[j]=Vnums[0]+nums[1]+...+nums[j] = Vnums[0]+nums[1]+...+nums[j]=V,且nums[j]+...+nums[t−1]=preSum−Vnums[j]+...+nums[t-1] =preSum- Vnums[j]+...+nums[t−1]=preSum−V。
所以在每个时刻我们都将HashMap[preSum−k]HashMap[preSum-k]HashMap[preSum−k]累加到我们的结果中。
class Solution:
def subarraySum(self, nums: 'List[int]', k: 'int') -> 'int':
res = 0
hashmap = {0:1}
presum = 0
for n in nums:
presum = n+presum
key = presum-k
if key in hashmap.keys():
res += hashmap[key]
hashmap[presum] = hashmap.get(presum,0)+1
return res
另一道题解法和本题相同:
Problem
In an array A of 0s and 1s, how many non-empty subarrays have sum S?
Example 1:
Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
Note:
A.length <= 30000
0 <= S <= A.length
A[i] is either 0 or 1.