LeetCode 题解工作台
元素和小于等于阈值的正方形的最大边长
给你一个大小为 m x n 的矩阵 mat 和一个整数阈值 threshold 。 请你返回元素总和小于或等于阈值的正方形区域的最大边长;如果没有这样的正方形区域,则返回 0 。 示例 1: 输入: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们可以先预处理得到二维前缀和数组 ,其中 $s[i + 1][j + 1]$ 表示矩阵 中从 $(0, 0)$ 到 $(i, j)$ 的元素和,那么对于任意的正方形区域,我们都可以在 的时间内得到其元素和。 接下来,我们可以使用二分查找的方法得到最大的边长。我们枚举正方形的边长 ,然后枚举正方形的左上角位置 $(i, j)$,那么我们可以得到正方形的元素和 ,如果 $v \leq thres…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个大小为 m x n 的矩阵 mat 和一个整数阈值 threshold。
请你返回元素总和小于或等于阈值的正方形区域的最大边长;如果没有这样的正方形区域,则返回 0 。
示例 1:

输入:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 输出:2 解释:总和小于或等于 4 的正方形的最大边长为 2,如图所示。
示例 2:
输入: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 输出:0
提示:
m == mat.lengthn == mat[i].length1 <= m, n <= 3000 <= mat[i][j] <= 1040 <= threshold <= 105
解题思路
方法一:二维前缀和 + 二分查找
我们可以先预处理得到二维前缀和数组 ,其中 表示矩阵 中从 到 的元素和,那么对于任意的正方形区域,我们都可以在 的时间内得到其元素和。
接下来,我们可以使用二分查找的方法得到最大的边长。我们枚举正方形的边长 ,然后枚举正方形的左上角位置 ,那么我们可以得到正方形的元素和 ,如果 ,那么说明存在边长为 的正方形区域的元素和小于或等于阈值,否则不存在。
时间复杂度 ,空间复杂度 。
class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
def check(k: int) -> bool:
for i in range(m - k + 1):
for j in range(n - k + 1):
v = s[i + k][j + k] - s[i][j + k] - s[i + k][j] + s[i][j]
if v <= threshold:
return True
return False
m, n = len(mat), len(mat[0])
s = [[0] * (n + 1) for _ in range(m + 1)]
for i, row in enumerate(mat, 1):
for j, x in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
l, r = 0, min(m, n)
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests the candidate's understanding of binary search in a 2D matrix context.
- question_mark
Evaluates how the candidate uses optimization techniques like prefix sums and sliding window.
- question_mark
Assesses problem-solving skills under constraints with a focus on space-time trade-offs.
常见陷阱
外企场景- error
Failing to optimize sum calculation by not using a prefix sum array.
- error
Not correctly implementing binary search over the possible side lengths, which could lead to inefficient solutions.
- error
Misunderstanding the use of sliding window in conjunction with the prefix sum array.
进阶变体
外企场景- arrow_right_alt
Modifying the threshold value to test performance with different limits.
- arrow_right_alt
Using different matrix configurations like sparse or fully populated matrices.
- arrow_right_alt
Adding constraints on the number range of matrix elements or threshold.