560. Subarray Sum Equals K (Medium) Google 考简化版,见325
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals tok.
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 1: PreSum + HashMap O(n); O(n)
/**
* PreSum + HashMap O(n); O(n)
* if we know SUM[0, i - 1] and SUM[0, j], then we can easily get SUM[i, j].
* To achieve this, we just need to go through the array,
* calculate the current sum and save number of all seen PreSum to a HashMap.
*/
public int subarraySum(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
int res = 0;
int sum = 0;
Map<Integer, Integer> map = new HashMap<>(); //key: preSum, value: the count of preSum
map.put(0, 1);
for (int num : nums) {
sum += num;
res += map.getOrDefault(sum - k, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return res;
}