无法解决具有和的相邻子阵列数的边缘情况

2024-06-06 20:53:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试解决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

Tags: key代码inforiftypecount测试用例
1条回答
网友
1楼 · 发布于 2024-06-06 20:53:43

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

再加上为什么你的解决方案不起作用,是因为你的总和永远不会重置。因此,可以检测0或1个解决方案。你知道吗

相关问题 更多 >