560. Subarray Sum Equals K (Medium)

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

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

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Solutions

class Solution {

    // The clever solution si to work the accumulated sums from preceding elements.
    // Then keep count of the occurrences for a particular sum. To make it more specifically,
    // nums[1,3,4,5,-5], countMap take turns add/update (0,1),(1,1),(4,1),(8,1),(13,1),(8,2)

    public int subarraySum(int[] nums, int k) {
        int ans = 0;
        if (nums == null || nums.length == 0) {
            return ans;
        }

        Map<Integer, Integer> countMap = new HashMap<>();

        // At the very beginning, no element summed and the initial sum should be 0,
        // the occurrence is 1.
        countMap.put(0, 1);

        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];

            // if the value (sum-k) used to be the sum of prior subarray. For instance,
            // assume current index is y and sum-k=3, sum of subarray [0:x] is 3, then we
            // could take subarray [x+1:y] as one of the answers.

            if (countMap.containsKey(sum - k)) {
                ans += countMap.get(sum - k);
            }

            if (!countMap.containsKey(sum)) {
                countMap.put(sum, 0);
            }

            countMap.put(sum, countMap.get(sum) + 1);
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""