leetcode-560-和为 K 的子数组
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的连续子数组的个数 。
示例 1:
输入:nums = [1,1,1], k = 2
输出:2
示例 2:
输入:nums = [1,2,3], k = 3
输出:2
提示: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000 -107 <= k <= 107
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/subarray-sum-equals-k
题解:
前缀和+哈希表优化
def subArraySum(nums, k):
presum = count = 0
length = len(nums)
presums = {}
presums[0] = 1
for i in range(length):
presum += nums[i]
if presum - k in presums:
count += presums[presum - k]
if presum not in presums:
presums[presum] = 1
else:
presums[presum] += 1
return count
本文来自博客园,作者:Hannah|Lee,转载请注明原文链接:https://www.cnblogs.com/hannahlee/p/16891941.html