560. Subarray Sum Equals K 等于K的子数组个数
Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals to k
.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3 Output: 2
哦,看错题了。是数组的个数,不是数组的长度。
把超出的元素去掉,就符合了。所以判断的是超出元素出现的次数
Your input
[1,1,1]
2
stdout
sum = 1
sum = 2
超出的元素sum - k = 0
超出的元素出现的次数preSum.get(sum - k) = 1
sum = 3
超出的元素sum - k = 1
超出的元素出现的次数preSum.get(sum - k) = 1
public class Solution {
public int subarraySum(int[] nums, int k) {
int sum = 0, result = 0;
Map<Integer, Integer> preSum = new HashMap<>();
preSum.put(0, 1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
System.out.println("sum = " + sum);
if (preSum.containsKey(sum - k)) {
result += preSum.get(sum - k);
System.out.println("超出的元素sum - k = " + (sum - k));
System.out.println("超出的元素出现的次数preSum.get(sum - k) = " + preSum.get(sum - k));
System.out.println(" ");
}
preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
}
return result;
}
}