题目
输入:nums = [1,1,1], k = 2
输出: 2
解释: 此题 [1,1] 与 [1,1] 为两种不同的情况
解法
- 前缀和 + 哈希表
- 多开辟一点空间
- preSum[j] = k + preSum[i] ; k = a[i+1] + ···+a[j] =>子数组和
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
# +- no using window
# using prefix sum
# preprocessing
n = len(nums)
preSum = [0]* (n+1)
pre= 0
for i in range(n):
pre += nums[i]
preSum[i+1] = pre
# main using hash map / dictionary
dic = {}
count = 0
for i in range(n+1):
if preSum[i] - k in dic:
count += dic[preSum[i] - k]
if preSum[i] not in dic:
dic[preSum[i]] = 1
else:
dic[preSum[i]] += 1
return count
该博客介绍了如何利用前缀和和哈希表解决寻找数组中和为k的子数组个数的问题。通过建立前缀和数组并利用哈希表存储前缀和出现的次数,可以有效地计算出符合条件的子数组数量。解法包括初始化前缀和数组,然后遍历数组,更新哈希表,并统计满足条件的子数组个数。
663

被折叠的 条评论
为什么被折叠?



