Subarray Sum Equals K
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
Input: nums = [1,1,1], k = 2
Output: 2Input: nums = [1,2,-1,-1,2], k = 2
Output: 4The 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].
Note
Using HashMap to store ( key : the PrefixSum, value : how many ways get to this prefix sum).
Check if PrefixSum - target exists in hashmap or not, if it does, we added up the ways of this key
For instance : in one path we have 1,2,-1,-1,2, then the prefix sum will be: 0, 1, 3, 2, 1, 3, let's say we want to find target sum is 2, then we will have{2}, {1,2,-1}, {2,-1,-1,2} and {2}ways.
Meaning:
PrefixSum2 - PrefixSum1 = Target
注意One Pass写法时候,其实没有把起始0加入循环,需要手动设置成map.put(0,1). PreSum数组则不用,因为它从index 0遍历到index len + 1。
Code
Last updated