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。
在遍历到时间
t
t
t 时,
n
u
m
s
[
0
]
+
n
u
m
s
[
1
]
+
.
.
.
+
n
u
m
s
[
t
−
1
]
=
p
r
e
S
u
m
nums[0]+nums[1]+...+nums[t-1] = preSum
nums[0]+nums[1]+...+nums[t−1]=preSum,在这个时刻之前共有
H
a
s
h
M
a
p
[
V
]
HashMap[V]
HashMap[V](
V
=
p
r
e
s
u
m
−
k
V = presum-k
V=presum−k)个indices
j
j
j 使得
n
u
m
s
[
0
]
+
n
u
m
s
[
1
]
+
.
.
.
+
n
u
m
s
[
j
]
=
V
nums[0]+nums[1]+...+nums[j] = V
nums[0]+nums[1]+...+nums[j]=V,且
n
u
m
s
[
j
]
+
.
.
.
+
n
u
m
s
[
t
−
1
]
=
p
r
e
S
u
m
−
V
nums[j]+...+nums[t-1] =preSum- V
nums[j]+...+nums[t−1]=preSum−V。
所以在每个时刻我们都将
H
a
s
h
M
a
p
[
p
r
e
S
u
m
−
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.