美文网首页
[Med] 560. Subarray Sum Equals K

[Med] 560. Subarray Sum Equals K

作者: Mree111 | 来源:发表于2019-10-24 13:30 被阅读0次

    Description

    Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

    Example 1:
    Input:nums = [1,1,1], k = 2
    Output: 2

    Solution

    1.build累积数组和
    2.遍历,过程中 先check sum in dict, then add value for dict (这样可以去重复

    class Solution:
        def subarraySum(self, nums: List[int], k: int) -> int:
            cnt =  0
            if len(nums)==0:
                return cnt
            max = [nums[0]]
            
            for i in range(1,len(nums)):
                max.append(nums[i]+max[-1])
            d = {0:1} #相当于从开始1st ele的sum满足K的sum
            for i in range(len(nums)):
                if max[i]-k in d:
                    cnt += d[max[i]-k]
                if max[i] in d:
                    d[max[i]]+=1
                else:
                    d[max[i]]=1
            return cnt
    

    相关文章

      网友评论

          本文标题:[Med] 560. Subarray Sum Equals K

          本文链接:https://www.haomeiwen.com/subject/olwrvctx.html