Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.css
Example 1:spa
Input:nums = [1,1,1], k = 2 Output: 2
Note:3d
方法一:(参考:https://zhuanlan.zhihu.com/p/36439368)code
考点:prefixSum arrayblog
维护一个前缀字典 prefix = {},该字典里的 key 为一个前缀和,相应的 value 为该前缀和出现的次数。令 prefixSum 表示当前位置的前缀和,因此在每一个位置咱们都获得了以这个位置为结尾的而且和等于 k 的区间的个数,也就是 prefixSum - k 在前缀字典里出现的次数。注意须要设 prefix[0] = 1。leetcode
1 class Solution(object): 2 def subarraySum(self, nums, k): 3 """ 4 :type nums: List[int] 5 :type k: int 6 :rtype: int 7 """ 8 cnt = 0 9 prefixSum = 0 10 prefix = {} 11 prefix[0] = 1 12 for n in nums: 13 prefixSum += n 14 cnt += prefix.get(prefixSum - k, 0) 15 prefix[prefixSum] = prefix.get(prefixSum, 0) + 1 16 return cnt