Day11 第一题
#######解题思路:两层循环,用暴力法解决(从不同起始位置开始的子数组)
class Solution {
public int subarraySum(int[] nums, int k) {
// 和为k的子数组的个数计数器count
int count = 0;
for(int j =0;j<nums.length;j++){
int sum = 0;
for(int i = j;i < nums.length;i++){
sum = sum + nums[i];
if(sum == k){
count++;
}
}
}
return count;
}
}
力扣官方解答:
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;
}
}
####### 巧妙的利用\(sum[i,j] = sum[0,j]- sum[0,i-1]\),所以有sum[i-1] = sum[j] - k
,所以\(i-1<j\),即contains判断要在hashmap加上sum[j]之前。