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