题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
解题思路:
方法一:
- 遍历每一个位置:统计每一行当前以当前位置结尾以的连续1的个数,保存在leftLength[i][j]中,方便后续计算矩阵的宽。
- 遍历每一个位置,计算以当前位置为右下角的矩阵的最大面积,对于当前位置 (i,j):
- 以第 j 列作为矩阵的左边界,依次向上寻找矩阵的高,矩阵的宽可以通过dp[i][j] 得到,
- 如果上面几行中某一行leftLength[i][j] = 0,那么显然,该行以及该行上面的行都不可能与下面的行构成矩阵,停止寻找高
AC代码
class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int result = 0;
int[][] leftLength = new int[m][n];
leftLength[0][0] = matrix[0][0] == '1' ? 1 : 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
leftLength[i][j] = j == 0 ?1: leftLength[i][j - 1] + 1;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (leftLength[i][j] != 0) {
int minLength = leftLength[i][j];
for (int k = i; k >= 0; k--) {
if (leftLength[i][j] == 0) {
break;
}
minLength = Math.min(minLength, leftLength[k][j]);
result = Math.max(result, minLength * (i - k + 1));
}
}
}
}
return result;
}
}
解法二:在方法一种,使用了一个 leftLength[ i ][ j ] 保存第i行中,以第j列结尾的连续1的个数,每然后依次对每个位置向上遍历寻找高,时间复杂度为 ,m是行数,n是列数,
可以把dp[i][j] 想象为 第i 行的柱状图的高度,n行一共有n个柱状图,那么问题就可以转化为这n个柱状图能够构成的最大矩阵高度,也就是力扣84题。
84题的解法参考:84. 柱状图中最大的矩形(单调栈)
一共有n列,只需要依次对第 i 列结尾的m个柱状图求解其构成的最大矩阵即可,一共计算 n 次
这种方法的时间复杂度可以优化为 O(mn):计算leftLength的时间复杂度为O(mn),使用单调栈计算每一列结尾的m个柱状图所构成的最大矩阵的时间复杂度为 O(m),一共计算n次,时间复杂度为O(mn),所以总的时间复杂度为 O(mn)
AC代码:
class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int result = 0;
int[][] leftLength = new int[m][n];
leftLength[0][0] = matrix[0][0] == '1' ? 1 : 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
leftLength[i][j] = j == 0 ? 1 : leftLength[i][j - 1] + 1;
}
}
}
for (int i = 0; i < n; i++) {//i 表示第几列
ArrayDeque<Integer> stack = new ArrayDeque<>();
for (int j = 0; j < m; j++) {
while (!stack.isEmpty() && leftLength[j][i] < leftLength[stack.peek()][i]) {
int top = stack.pop();
int width;
if (stack.isEmpty()) {
width = j;
} else {
width = j - stack.peek() - 1;
}
result = Math.max(result, width * leftLength[top][i]);
}
stack.push(j);
}
while (!stack.isEmpty()) {
int top = stack.pop();
int width;
if (stack.isEmpty()) {
width = m;
} else {
width = m - stack.peek() - 1;
}
result = Math.max(result, width * leftLength[top][i]);
}
}
return result;
}
}