Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k

核能气质少年 提交于 2021-02-11 12:46:43

问题


def subarraySum(self, nums: List[int], k: int) -> int:
    count = 0
    target = k
    self.cal(nums,target,count,k)
    return count
def cal(nums,target, count,k):
    if target == 0:
        count = count+1
        target = k
        return count,target
    if target<0:
        return 
        
    for i in range(len(nums)):
        self.cal(nums[:i]+nums[i+1:],target-nums[i],count,k)

''' here when the target < 0 i want to break the loop and for example if there is array 1,2,3 and my target is 2 i will go to the loop first add 1 next again add 2 which is not possible so i want to break the next checking series and want to start from 2'''


回答1:


You could try to use the prefix idea and defaultdict() to solve this Subarray Sum problem more elegantly and efficiently. It's depending on the prefix sum idea, the code is easy to follow, you could try to run it with different data. In the dc[v] we store all prefix sum, the num. of prev. prefix sum with value v. Then it loops and the array to see if new num. w coming has value that satisfies w-v equal k then we got a new count(pair).

from collections import defaultdict
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        dc = defaultdict(int)
        sum_ = 0
        dc[0] = 1
        result = 0
        for n in nums:
            sum_ += n
            if sum_ - k in dc:
                result += dc[sum_ - k]
            dc[sum_] += 1
        return result


来源:https://stackoverflow.com/questions/65915612/given-an-array-of-integers-nums-and-an-integer-k-return-the-total-number-of-con

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!