https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/

讲解的详细

看这道题是为了解决https://leetcode.com/problems/path-sum-iii/

 

import java.util.HashMap;
import java.util.Map;

public class test {
    static int findSubarraySum(int arr[],int sum){
        Map<Integer,Integer> preSum=new HashMap<>();
        int res=0,curSum=0;
        for(int a:arr) {
            curSum+=a;
            if(curSum==sum){
                res++;
                continue;
            }
            if(preSum.containsKey(curSum-sum)){//如果当前的curSum比sum大,就去找是否之前加过这个差值,那么为了等于sum,我们现在可以知道,只要之前不加这个差值就可以
                res+=preSum.get(curSum-sum);
            }
            preSum.put(curSum,preSum.getOrDefault(curSum,0)+1);
        }
        return res;
    }
    public static void main(String[] args) {
        int[] arr={10, 2, -2, -20, 10};
        System.out.println(findSubarraySum(arr,-10));
    }
}