Leetcode 560. Subarray Sum Equals K

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Subarray Sum Equals K

2. Solution

解析:Version 1,使用前缀和来解决,遍历数组,求前缀和,统计前缀和的次数并保存到字典中,当碰到差值在字典中存在时,则意味着当前数组减去之前的前缀和数组等于k,将次数加到count中,更新前缀和的次数。注意,假设第一个数就等于k,此时数组中没有差值0的次数,因此stat[0]=1

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
total = 0
count = 0
stat = collections.defaultdict(int)
stat[0] = 1
for i in range(n):
total += nums[i]
count += stat[total - k]
stat[total] += 1
return count

Reference

  1. https://leetcode.com/problems/subarray-sum-equals-k/
如果有收获,可以请我喝杯咖啡!