其他分享
首页 > 其他分享> > LeetCode-【前缀和】解题技巧

LeetCode-【前缀和】解题技巧

作者:互联网

560. 和为K的子数组

class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        sum_ = {}
        sum_[0] = 1
        ret = 0
        curr_sum = 0
        for i in nums:
            curr_sum+=i
            ret+=sum_.get(curr_sum-k,0)
            sum_[curr_sum] = sum_.get(curr_sum,0)+1
        return ret

1248. 统计「优美子数组」

class Solution(object):
    def numberOfSubarrays(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        dict_ = {}
        dict_[0]=1
        curr_sum = 0
        ret = 0
        for i in nums:
            curr_sum+=(i%2)
            ret+=dict_.get(curr_sum-k,0)
            dict_[curr_sum]=dict_.get(curr_sum,0)+1
        return ret

974. 和可被 K 整除的子数组

class Solution(object):
    def subarraysDivByK(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        dict_ = {}
        dict_[0]=1
        ret = 0
        curr_sum = 0
        for i in A:
            curr_sum+=i
            # 前缀和除以K的余数
            key = (curr_sum % K+K) % K
            ret+=dict_.get(key,0)
            dict_[key]=dict_.get(key,0)+1
        return ret

523. 连续的子数组和

class Solution(object):
    def checkSubarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dict_ = {}
        # 与下标为1的元素刚好满足要求(》=2)
        dict_[0]=-1
        curr_sum=0
        for i,v in enumerate(nums):
            curr_sum+=v
            # 余数相同,则表明至少n*k
            if k!=0:
                curr_sum%=k
            if curr_sum in dict_:
                if i-dict_[curr_sum]>1:
                    return True
            else:
                dict_[curr_sum]=i
        return False

 

标签:curr,前缀,nums,int,sum,ret,dict,解题技巧,LeetCode
来源: https://blog.csdn.net/lanzhihui_10086/article/details/113828292