力扣之前缀和 2022-02-28~03-06

前缀和

重点:题目中出现“连续子数组”字样
https://leetcode-cn.com/problems/subarray-sum-equals-k/solution/de-liao-yi-wen-jiang-qian-zhui-he-an-pai-yhyf/

前缀和

560. 和为 K 的子数组

'''
连续子数组,假设是nums[i:j+1],那么其实是total[j] - total[i-1]
'''
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        total = 0
        hash_total = {}
        hash_total[0] = 1
        res = 0
        for i in range(len(nums)):
            total += nums[i]
            if total-k in hash_total:
                res += hash_total[total-k]
            if total in hash_total:
                hash_total[total] += 1
            else:
                hash_total[total] = 1
        return res

1248. 统计「优美子数组」

'''
和上面的一模一样
'''
class Solution:
    def numberOfSubarrays(self, nums: List[int], k: int) -> int:
        presum = 0
        hash_pre = {}
        hash_pre[0] = 1
        res = 0
        for i in range(len(nums)):
            if nums[i] & 1 == 1:
                presum += 1
            if presum-k in hash_pre:
                res += hash_pre[presum-k]
            if presum in hash_pre:
                hash_pre[presum] += 1
            else:
                hash_pre[presum] = 1
        return res

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

'''
和上面的还是一样
注意一点是这里需求的是数组和是k的倍数,也就是
presum[right] - presum[left] = n*k
而此时presum都是小于k的,因此在这里n=0
也就是满足的条件是presum[right] - presum[left] = 0
也就是
if presum in hash_pre:
    res += hash_pre[presum]
'''
class Solution:
    def subarraysDivByK(self, nums: List[int], k: int) -> int:
        presum = 0
        res = 0
        hash_pre = {}
        hash_pre[0] = 1
        for i in range(len(nums)):
            presum = (presum + nums[i]) % k
            if presum in hash_pre:
                res += hash_pre[presum]
            if presum in hash_pre:
                hash_pre[presum] += 1
            else:
                hash_pre[presum] = 1
        return res

523. 连续的子数组和

'''
和上面一样,也是求k的倍数,因为子数组大小至少为 2 
因此使用last_pre来使得nums[i:i+1]的情况不存在
'''
class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        presum = 0
        hash_pre = set()
        hash_pre.add(0)
        last_presum = 0
        for i in range(len(nums)):
            presum = (presum + nums[i]) % k
            if presum in hash_pre and i != 0:
                return True
            hash_pre.add(last_presum)
            last_presum = presum
        return False

930. 和相同的二元子数组

'''
也和上面一样
'''
class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        presum = 0
        hash_pre = {}
        hash_pre[0] = 1
        res = 0
        for i in range(len(nums)):
            presum += nums[i]
            if  presum - goal in hash_pre:
                res += hash_pre[presum-goal]
            if presum in hash_pre:
                hash_pre[presum] += 1
            else:
                hash_pre[presum] = 1
        return res

你可能感兴趣的:(力扣之前缀和 2022-02-28~03-06)