0560. Subarray Sum Equals K

https://leetcode.com/problems/subarray-sum-equals-k

Description

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

Constraints:

  • 1 <= nums.length <= 2 * 104

  • -1000 <= nums[i] <= 1000

  • -107 <= k <= 107

ac

similar: https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/

class Solution {
    public int subarraySum(int[] nums, int k) {
        // edge cases
        if (nums == null || nums.length == 0) return 0;

        int count = 0;

        Map<Integer, Integer> map = new HashMap<>();
        map.put(0,1); // init
        int currSum = 0;
        for (int i = 0; i < nums.length; i++) {
            currSum += nums[i];
            int oldSum = currSum - k;
            count += map.getOrDefault(oldSum, 0);
            map.put(currSum, map.getOrDefault(currSum, 0) + 1);
        }

        return count;
    }
}

Last updated