class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0 || matrix[0].length == 0)
return 0;
int col = matrix[0].length;
int row = matrix.length;
int res = 0;
int[] heights = new int[col];
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(matrix[i][j] == '1')
heights[j] += 1;
else
heights[j] = 0;
}
res = Math.max(res, largestRectangleArea(heights));
}
return res;
}
/**
* 84.柱状图中最大的矩形
*/
public int largestRectangleArea(int[] heights) {
// //1、暴力解
// int res = 0;
// int h = 0;
// for(int i = 0; i < heights.length; i++){
// int w = 1;
// h = heights[i];
// int j = i;
// while(--j >= 0 && heights[j] >= h)
// w++;
// j = i;
// while(++j < heights.length && heights[j] >= h)
// w++;
// res = Math.max(res, w * h);
// }
// return res;
//2、单调栈
int[] temp = new int[heights.length + 2];
for(int i = 1; i < temp.length - 1; i++){
temp[i] = heights[i - 1];
}
Stack<Integer> stack = new Stack<>();
int res = 0;
for(int i = 0; i < temp.length; i++){
while(!stack.isEmpty() && temp[i] < temp[stack.peek()]){
int h = temp[stack.pop()];
res = Math.max(res, h * (i - 1 - stack.peek()));
}
stack.push(i);
}
return res;
}
}
LeetCode85.最大矩形
最新推荐文章于 2024-02-03 16:33:29 发布