无法求解和 k 的连续子数组数量的边缘情况



我一直在尝试解决leetcode上的"子数组总和等于K"问题。但是,我无法使用以下代码解决某些测试用例:

from collections import defaultdict
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sumTable = defaultdict(lambda : 0) 
count = 0
totalSum = 0
for i in range(0,len(nums)):
totalSum += nums[i]
if(totalSum==k):
count += 1
sumTable[totalSum] += 1
for key in sumTable:
# print(key)
if (key-k) in sumTable:
count += sumTable[key-k]
return count

在 Github 上找到了这个解决方案

import collections
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = 0
accumulated_sum = 0
lookup = collections.defaultdict(int)
lookup[0] += 1
for num in nums:
accumulated_sum += num
result += lookup[accumulated_sum - k]
lookup[accumulated_sum] += 1
return result

另外,为什么您的解决方案不起作用,是因为您的 TotalSum 永远不会重置。因此,您检测到 0 或 1 个解决方案。

最新更新