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:

Input:nums = [1,1,1], k = 2
Output: 2

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

方法一:(参考:https://zhuanlan.zhihu.com/p/36439368

考点:prefixSum array

维护一个前缀字典 prefix = {},该字典里的 key 为一个前缀和,相应的 value 为该前缀和出现的次数。令 prefixSum 表示当前位置的前缀和,所以在每个位置我们都得到了以这个位置为结尾的并且和等于 k 的区间的个数,也就是 prefixSum - k 在前缀字典里出现的次数。注意需要设 prefix[0] = 1

 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 

 

posted @ 2019-08-21 01:35  Aparecium  阅读(198)  评论(0编辑  收藏  举报