LeetCode 560. 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:
1 | Input:nums = [1,1,1], k = 2 |
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
因为数组中可能出现负数,所以不能用双指针。
用一个哈希表记录所有前缀和出现的下标,然后对于每一个下标i
对应的前缀和sum
,找到sum+k
出现的下标,其中大于等于i的下标的个数就是从i开始的和为k的连续子串的个数。
1 | class Solution { |