LeetCode 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold 1074. 二维前缀

231 篇文章 0 订阅

Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.

 

Example 1:

Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.

Example 2:

Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0

Example 3:

Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
Output: 3

Example 4:

Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
Output: 2

 

Constraints:

  • 1 <= m, n <= 300
  • m == mat.length
  • n == mat[i].length
  • 0 <= mat[i][j] <= 10000
  • 0 <= threshold <= 10^5

-------------------------------------------------

前缀法很容易想到,但是到了二维,要先明确两点:

  1. 二维的前缀accu[x][y]=accu[x-1][y]+accu[x][y-1]-accu[x-1][y-1]+mat[x][y],简而言之就是行减一,列减一,再减去行列都减一重叠那部分,这种写法可以避免if else
  2. 前缀的差表示为arr[i]-arr[j],边长刚好是i-j,j可能是-1,在这种情况下直接让arr[j]为0,新定义一个if else来判断这种情况即可

所以,很容易想到几种解法:

解法A: 某一维上枚举,另外一维度上滑动窗口,这样的复杂度是min(rows,cols)^2*max(rows,cols)。

解法B: 二维循环枚举所有行列,利用1可以O(1)求出前缀和,利用2可以根据边长O(1)求出某个正方形的和,根据边长二分正方形的面积,让他<=阈值,相当于求最后一个<=,也就是upper_bound-1,复杂度为rows*cols*log(rows*cols),codes如下:

class Solution:
    def maxSideLength(self, mat, threshold: int) -> int:
        def accu(x,y):
            return mat[x][y] if x>=0<=y else 0
        rows,cols,edge = len(mat),len(mat[0]) if mat else 0,0
        if (rows == 0 or cols == 0):
            return 0
        for i in range(rows):
            for j in range(cols):
                mat[i][j] += accu(i-1,j)+accu(i,j-1)-accu(i-1,j-1)
                l,r = edge,min(i,j)+1
                #upper_bound-1
                while (l<=r):
                    mid = l + ((r-l)>>1)
                    fx = accu(i,j)-accu(i-mid,j)-accu(i,j-mid)+accu(i-mid,j-mid)
                    if (fx <= threshold):
                        l = mid+1
                    else:
                        r = mid-1
                if (l-1>edge):
                    edge = l-1
        return edge
s = Solution()
print(s.maxSideLength(mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184))

解法C:解法C是对B更好的改进,在新位置(i,j),尝试放比之前正方形边长edge大1的新正方形。为什么是比之前最好的edge大1呢?而不是大2呢?其实用反证法很容易证明。假设新正方形放得下edge+2,那么新正方形行-1、列-1的位置一定放得下edge+1的正方形,这个之前最好的正方形边长为edge矛盾。因此,只有edge+1有必要尝试,<edge+1的正方形没有必要试了,edge+2、edge+3。。这些更没有必要试了。。。这样时间复杂度成功降到O(rows*cols)

class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        def accu(x,y):
            return mat[x][y] if x>=0<=y else 0
        rows,cols = len(mat),len(mat[0]) if mat else 0
        if (rows == 0 or cols == 0):
            return 0
        edge = 0
        for i in range(rows):
            for j in range(cols):
                mat[i][j] += accu(i-1,j)+accu(i,j-1)-accu(i-1,j-1)
                
                if (i>=edge<=j and accu(i,j)-accu(i-edge-1,j)-accu(i,j-edge-1)+accu(i-edge-1,j-edge-1)<=threshold):
                    edge += 1
        return edge  

-----------------------------------------------------------------------------------------------------

但是对于下面题目来说,就没法找到O(n^3)以下的解法了,老老实实利用前缀走起:

Given a matrix, and a target, return the number of non-empty submatrices that sum to target.

A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.

Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.

 

Example 1:

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.

Example 2:

Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.

 

Note:

  1. 1 <= matrix.length <= 300
  2. 1 <= matrix[0].length <= 300
  3. -1000 <= matrix[i] <= 1000
  4. -10^8 <= target <= 10^8
from collections import defaultdict
class Solution:
    def numSubmatrixSumTarget(self, matrix, target) -> int:
        def A(x,y):
            nonlocal a
            return a[x][y] if x>=0<=y else 0

        rows,cols = len(matrix),len(matrix[0]) if matrix else 0
        b = matrix if (rows <= cols) else [[matrix[j][i] for j in range(rows)] for i in range(cols)]
        rows,cols = len(b),len(b[0])

        if (rows == 0 or cols == 0):
            return 0
        a = [[0 for j in range(cols)] for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                a[i][j] = b[i][j]+A(i,j-1)+A(i-1,j)-A(i-1,j-1)
        res = 0
        for x1 in range(rows):
            for x2 in range(x1,rows):
                dic,px = defaultdict(int),0
                dic[0] = 1 #bug2: forget this line
                for y in range(cols):
                    px = A(x2,y)-A(x1-1,y) #bug1: px += A(x2,y)-A(x1-1,y
                    res += dic[px-target]
                    dic[px] += 1
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值