我一直在尝试解决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上找到了这个解决方案
再加上为什么你的解决方案不起作用,是因为你的总和永远不会重置。因此,可以检测0或1个解决方案。你知道吗
相关问题 更多 >
编程相关推荐