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
Solution: PreSum + HashMap
思路:
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
public class Solution {
public int subarraySum(int[] nums, int k) {
int sum = 0, result = 0;
Map<Integer, Integer> preSumCount = new HashMap<>();
preSumCount.put(0, 1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (preSumCount.containsKey(sum - k)) {
result += preSumCount.get(sum - k);
}
preSumCount.put(sum, preSumCount.getOrDefault(sum, 0) + 1);
}
return result;
}
}