Leetcode 560.和为K的子数组
1 题目描述(Leetcode题目链接)
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
- 数组的长度为 [1, 20,000]。
- 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
2 题解
前缀和+哈希表。记录到当前为止的数组和 ,如果 在表中,则子数组个数加上 出现的次数。
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
prefix = {0:1}
s = 0
cnt = 0
for num in nums:
s += num
if s-k in prefix:
cnt += prefix[s-k]
if s in prefix:
prefix[s] += 1
else:
prefix[s] = 1
return cnt