题目:给定一个仅包含
0
和1
、大小为rows x cols
的二维二进制矩阵,找出只包含1
的最大矩形,并返回其面积。
思路: 用一个数组记录贴地的柱子高度,从row=0,开始一直到矩阵最底一行。之后计算柱子面积。算是复用代码
class Solution {
public int maximalRectangle(char[][] matrix) {
/*
这题与84柱子中矩形的最大面积十分类似
不过是上一题问题的基础上求多个矩形的最大值
等价于求rec[0,j],j∈[0,row-1]组成的柱子的中可以勾勒出的最大矩形面积
注意:matrix的类型是char!
*/
// 阴间案例
if(matrix == null || matrix.length == 0) {
return 0;
}
int row = matrix.length;
int res = 0;
// 仅仅记录贴地的柱子高度,不贴地为0
int[] heights = new int[matrix[0].length];
for(int i = 0; i < row; i++) {
// 计算res[0,j]的柱子高度
for(int j = 0; j < matrix[i].length; j++) {
// 注意这里是'0'字符类型!坑了我好久
heights[j] = matrix[i][j] == '0' ? 0 : (heights[j] + 1);
}
res = Math.max(res, getMaxArea(heights));
}
return res;
}
/*
84题单调栈解法模板
*/
private int getMaxArea(int[] heights) {
Deque<Integer> stack = new LinkedList<>();
int[] newHeights = new int[heights.length + 2];
System.arraycopy(heights, 0, newHeights, 1, heights.length);
int res = 0;
for(int i = 0; i < newHeights.length; i++) {
while(!stack.isEmpty() && newHeights[i] < newHeights[stack.peekFirst()]) {
int cur_height = newHeights[stack.pollFirst()];
int cur_width = i - stack.peekFirst() - 1;
res = Math.max(res, cur_height * cur_width);
}
stack.addFirst(i);
}
return res;
}
}