题目描述:
思路一:
本题可以通过前缀和(Prefix Sum)与哈希表(Hash Map)相结合的方法高效解决。这种方法的核心思想是利用前缀和来快速计算任意子数组的和,并通过哈希表记录每个前缀和出现的次数,从而快速找到符合条件的子数组数量。以下是具体的解题步骤:
- 初始化
- 创建一个哈希表 pre_sum_hashmap 用来存储每个前缀和及其出现的次数。
- 初始化时将 {0: 1} 加入哈希表,表示前缀和为 0 的情况出现了1次。这对于处理从数组起始位置开始的子数组非常重要。
- 初始化计数器 total 为 0,用于记录符合条件的子数组数量。
- 初始化变量 current_sum 为 0,用于累加当前前缀和。
- 遍历数组
- 对于数组中的每一个元素,执行以下操作:
- 更新 current_sum,即加上当前元素的值。
- 检查 current_sum - k 是否存在于 pre_sum_hashmap 中。如果存在,则意味着存在一个或多个之前的前缀和使得它们与当前前缀和之间的差等于 k,这些前缀和之间对应的子数组之和即为 k。根据哈希表中的计数,更新 total。
- 将当前的 current_sum 添加到 pre_sum_hashmap 中,记录其出现的次数。如果之前没有出现过,则设置为 1;如果已经存在,则计数加 1。
- 遍历完成后,返回total即可,
- 对于数组中的每一个元素,执行以下操作:
代码实现如下:
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
pre_sum = []
pre_sum_hashmap = {0: 1}
total = 0
current_sum = 0
# 构造前缀和列表并更新哈希表
for i in range(len(nums)):
current_sum += nums[i]
pre_sum.append(current_sum)
# 检查“之前的”所有前缀和中是否存在current_sum - k
if (current_sum - k) in pre_sum_hashmap:
total += pre_sum_hashmap[current_sum - k]
# 更新当前前缀和出现的次数
if current_sum not in pre_sum_hashmap:
pre_sum_hashmap[current_sum] = 1
else:
pre_sum_hashmap[current_sum] += 1
return total
执行用时如下: