题目描述:
给你一个大小为 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
示例 3:
输入:mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
输出:3
示例 4:
输入:mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
输出:2
提示:
1 <= m, n <= 300
m == mat.length
n == mat[i].length
0 <= mat[i][j] <= 10000
0 <= threshold <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
emm这道题和之前的差不多,首先我们将每行的前i列和存放在mat[row][i]中,然后我们从i,j开始,往前递减,看是否满足其和小于等于threshold,看代码比较简单:
class Solution {
public int maxSideLength(int[][] mat, int threshold) {
if (mat.length == 0 || mat[0].length == 0) {
return 0;
}
int result = 0;
for (int i = 0; i < mat.length; i++) {
int[] ints = mat[i];
for (int j = 1; j < ints.length; j++) {
int anInt = ints[j];
if (anInt <= threshold) {
result = 1;
}
mat[i][j] += ints[j - 1];
}
}
if (result == 0) {
return 0;
}
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
int tes = get(mat,i,j,threshold);
result = Math.max(result,tes);
}
}
return result;
}
public int get(int [][]mat,int x,int y,int thread){
// int result = 0;
int temx = x;
int temy = y;
if(x == 0 || y == 0){
if(y != 0){
return mat[x][y] - mat[x][y - 1] <= thread ? 1: 0;
}else
return mat[x][y] <= thread ? 1: 0;
}
int len = 1;
x--;
y--;
while (x >= 0 && y >= 0){
int tem = 0;
for (int i = x; i <= temx; i++) {
if(y != 0){
tem = tem + mat[i][temy] - mat[i][y - 1];
}else
tem += mat[i][temy];
}
x--;
y--;
if(tem <= thread){
len ++;
}
else
break;
}
return len;
}
}