子数组是连续的 如果 从 i到j的连续子数组和为k,那么计数加1
1、通过前缀和数组来提高获取子数组和的效率
2、通过map来记录0....i的前缀和出现的次数
class Solution {
public int subarraySum(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
Map<Integer, Integer> preSumTimesMap = new HashMap<>();
preSumTimesMap.put(0, 1);
int all = 0; // 0..i
int ans = 0;
for (int i = 0; i < nums.length; i++) {
all += nums[i]; // 0....i 整体的前缀和
//all 代表 0....i 的整体前缀和数组 如果 map中包含 all-k的key
//说明存在一个index 他的0到index 前缀和位all-k
// 那么 index+1 到i 的前缀和就是 all的前缀和-index的前缀和
//all-(all-k)= k 所以ans+1
if (preSumTimesMap.containsKey(all - k)) {
ans += preSumTimesMap.get(all - k);
}
//如果不包含就+1
if (!preSumTimesMap.containsKey(all)) {
preSumTimesMap.put(all, 1);
} else {
//包含这个前缀和 就是+1
preSumTimesMap.put(all, preSumTimesMap.get(all) + 1);
}
}
return ans;
}
}