560. Subarray Sum Equals K

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

Solution

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
  var map = {};
  var len = nums.length;
  var sum = 0;
  var res = 0;

  map[0] = 1;

  for (var i = 0; i < len; i++) {
    sum += nums[i];
    res += (map[sum - k] || 0);
    map[sum] = (map[sum] || 0) + 1;
  }

  return res;
};

Explain:

i 处,map[key] 表示 0 ~ i 中和为 key 的子数组数量。

i 处,0 ~ i 的和为 sum,此前和为 k 的子数组个数为 map[sum - k]

Complexity: