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
public int subarraySum(int[] nums, int k) {标签:map,nums,560,res,Sum,int,Subarray,sum From: https://www.cnblogs.com/MarkLeeBYR/p/17235776.html
Map<Integer, Integer> map = new HashMap<>(); // 使用map记录出现同样的和的次数, 对每个i计算累计和sum并判断map内是否有sum-k
map.put(0,1);
int sum = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
res += map.getOrDefault(sum - k, 0);//注意必须是sum-k,
map.put(sum,map.getOrDefault(sum,0) + 1);
}
return res;
}