20240314-前缀和

基本推导公式

因此得出二维前缀和预处理公式
s[i][j] = s[i - 1][j] + s[i][j - 1 ] + a[i] [j] - s[i - 1][j - 1]

因此二维前缀和的结论为:
以(x1, y1)为左上角,(x2, y2)为右下角的子矩阵的和为:
s[x2, y2] - s[x1 - 1, y2] - s[x2, y1 - 1] + s[x1 - 1, y1 - 1]

给定区间[l, r ],让我们把a数组中的[l, r] 区间中的每一个数都加上c,即 a[l] + c , a[l + 1] + c , a[l + 2] + c , a[r] + c;
b[l] + c,效果使得a数组中 a[l] 及以后的数都加上了c
b[r + 1] - c,让a数组中 a[r + 1]及往后的区间再减去c
给a数组中的[ l, r] 区间中的每一个数都加上c,只需对差分数组b做 b[l] + = c, b[r+1] - = c 。时间复杂度为O(1), 大大提高了效率。

例题1 长度最小的子数组

https://leetcode.cn/problems/minimum-size-subarray-sum/

#滑动窗口
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        left,right=0,0
        cnt=0
        res=len(nums)+1
        while right<len(nums):
            cnt+=nums[right]
            while cnt>=target:
                res=min(res,right-left+1)
                cnt-=nums[left]
                left+=1
            right+=1
        return 0 if res==len(nums)+1 else res

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0,right=0,cnt=0,res=nums.length+1;
        while (right<nums.length){
            cnt+=nums[right];
            while (cnt>=target){
                cnt-=nums[left];
                res = res>right-left+1?right-left+1:res;
                left+=1;
            }
            right+=1;
        }
        return res==nums.length+1?0:res;
    }
}

例题2 除自身以外数组的乘积

https://leetcode.cn/problems/product-of-array-except-self/description/

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        dpleft=[1 for _ in range(len(nums))]
        dpright=[1 for _ in range(len(nums))]
        answer=[1 for _ in range(len(nums))]
        for i in range(1,len(nums)):
            dpleft[i]=dpleft[i-1]*nums[i-1]
        for i in range(len(nums)-2,-1,-1):
            dpright[i]=dpright[i+1]*nums[i+1]
        for i in range(len(nums)):
            answer[i]=dpleft[i]*dpright[i]
        return answer
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        dpleft=[1 for _ in range(len(nums))]
        answer=[1 for _ in range(len(nums))]
        right=1
        for i in range(1,len(nums)):
            dpleft[i]=dpleft[i-1]*nums[i-1]
        for i in range(len(nums)-1,-1,-1):
            answer[i]=right*dpleft[i]
            right=right*nums[i]
        return answer
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值