class Solution {
// 方法1:暴力,两重for循环,第一重for循环代表开头,第二重for循环代表结尾,遍历求和, 时间复杂度O(n^2)
// 方法2:前缀和+HashMap,类似于两数之和,用hashmap可以降时间复杂度
//
public int subarraySum(int[] nums, int k) {
int pre = 0;
int count = 0;
HashMap<Integer,Integer> hs = new HashMap<>(); // hashput存储的是前缀和
hs.put(0,1); //连续子数组,什么都没有默认为0
for (int i = 0; i < nums.length; i++) {
pre += nums[i];
if (hs.containsKey(pre - k)) {
count += hs.get(pre - k);
}
hs.put(pre, hs.getOrDefault(pre, 0) + 1);
}
return count;
}
}