基本推导公式
因此得出二维前缀和预处理公式
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,0cnt=0res=len(nums)+1while right<len(nums):cnt+=nums[right]while cnt>=target:res=min(res,right-left+1)cnt-=nums[left]left+=1right+=1return 0 if res==len(nums)+1 else resclass 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=1for 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