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:
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].
解法1:O(N) Time + O(N) Space
这题和2Sum的思路有点像。首先是一道continuous sum的题,可以考虑用prefix sum的办法。
每次计算一个累加和,假设为sum,sum-presum=k也就意味着,sum-k=presum,如果我们用一个hashtable存储每一个presum出现的次数,那就可以指导对于任意一个sum,其满足要求的presum是否出现过,并且出现过几次。这一点和2sum是一样的,只是一个用加法一个用减法。
C++
Java