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

Solution: preSum + hashmap。注意不能用hashset,eg: [0,0,0,0,0,0,0,0,0,0] 0

    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> hashmap = new HashMap<>();
        int count = 0, preSum = 0;
        hashmap.put(0, 1);
        for (int num : nums) {
            preSum += num;

            count += hashmap.getOrDefault(preSum - k, 0);

            hashmap.put(preSum, hashmap.getOrDefault(preSum, 0) + 1);
        }
        return count;
    }

results matching ""

    No results matching ""