Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

560. Subarray Sum Equals K #162

Open
Tcdian opened this issue May 15, 2020 · 1 comment
Open

560. Subarray Sum Equals K #162

Tcdian opened this issue May 15, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 15, 2020

560. Subarray Sum Equals K

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

Example

Input:nums = [1,1,1], k = 2
Output: 2

Note

  • 数组的长度为 [1, 20,000]。
  • 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
@Tcdian
Copy link
Owner Author

Tcdian commented May 15, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
    const cache = new Map();
    let prefixSum = 0;
    let result = 0;
    cache.set(0, 1);
    for (let i = 0; i < nums.length; i++) {
        prefixSum += nums[i]
        if (cache.has(prefixSum - k)) {
            result += cache.get(prefixSum - k);
        }
        cache.set(prefixSum, (cache.get(prefixSum) || 0) + 1)
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant