Skip to content

560. 和为K的子数组 #36

@bt2ee

Description

@bt2ee

题目

给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。

示例

示例 1:

输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。

解题

解题方法

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
  let presumK = 0,
    count = 0
  const map = new Map()
  map.set(0, 1)

  for (let i = 0; i < nums.length; i++) {
    presumK += nums[i]
    if (map.has(presumK - k)) count += map.get(presumK - k)
    map.set(presumK, (map.get(presumK) || 0) + 1)
  }
  return count
};

相关题目

974. 和可被 K 整除的子数组
523. 连续的子数组和

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions