思路:
1.前缀和+枚举(ON2)
2.前缀和+哈希(ON)
1:Acode:
class Solution {
public int subarraySum(int[] nums, int k) {
int[] pre = new int[nums.length];
int ans=0;
pre[0]=nums[0];
if(pre[0]==k)ans++;
for (int i = 1; i < nums.length; i++) {
pre[i]=pre[i-1]+nums[i];
if(pre[i]==k)ans++;
}
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if(pre[j]-pre[i]==k)ans++;
}
}
return ans;
}
}
2:
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0, pre = 0;
HashMap < Integer, Integer > mp = new HashMap < > ();
mp.put(0, 1);
for (int i = 0; i < nums.length; i++) {
pre += nums[i];
if (mp.containsKey(pre - k)) {
count += mp.get(pre - k);
}
mp.put(pre, mp.getOrDefault(pre, 0) + 1);
}
return count;
}
}
over~