560 和为K的子数组

本文最后更新于:2021年1月6日 下午

给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。

示例 1 :

1
2
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1][1,1] 为两种不同的情况。

说明 :

  1. 数组的长度为 [1, 20,000]。
  2. 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。

Solution

参考:《算法小抄》4.9 、**@mu-ren-6**

  • 利用哈希表存储前缀和
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# @lc code=start
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
if not nums: return 0
dSum = {0:1}
preSum = 0
ans = 0
for num in nums:
preSum+=num
if dSum.get(preSum-k):
ans += dSum[preSum-k]
if dSum.get(preSum):
dSum[preSum] += 1
else:
dSum[preSum] = 1
return ans
# @lc code=end

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!