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].
--------------------------------------------------------------------------------
反应有些慢啊。。。
注意命名,如果输入参数有k这种,用dict的时候就小心了,否则容易出问题。。。
另外注意dict.get(k,default_value)的写法
class Solution:
def subarraySum(self, nums, k) -> int:
i, res, cursum, l = 0, 0, 0, len(nums)
if (l <= 0):
return 0
history = {0:1}
for i in range(l):
cursum += nums[i]
prevk = cursum-k
prevk = history.get(prevk,0)
res += prevk
history[cursum] = history.get(cursum, 0)+1
return res
s = Solution()
print(s.subarraySum([1,1,1],2))