LeetCode-085-最大矩形

思路
这道题和84题是同类问题,只是需要我们自己更新每一行的高度数组,并计算到达当前行的最大面积
代码
class Solution {
public int maximalRectangle(char[][] matrix) {
int rows=matrix.length;
if(rows==0)return 0;
int cols=matrix[0].length;
int []heights=new int[cols];
int res=0;
for(int i=0;i<rows;i++){
//每一行更新高度
for(int j=0;j<cols;j++){
//连续都是1则加1
if(matrix[i][j]=='1'){
heights[j]++;
}
//断开则归0
else heights[j]=0;
}
res=Math.max(res,largestRectangleArea(heights));
}
return res;
}
//直接调用84题的函数
public int largestRectangleArea(int[] heights) {
//增加首尾用于放置高度为0的柱,保证边界条件,且不用判断栈空
int []arr=new int[heights.length+2];
for(int i=0;i<heights.length;i++){
arr[i+1]=heights[i];
}
int res=0;
Stack<Integer> st=new Stack<>();
for(int i=0;i<arr.length;i++){
while(!st.isEmpty()&&arr[i]<arr[st.peek()]){
int h=arr[st.pop()];
int w=i-st.peek()-1;
res=Math.max(res,h*w);
}
st.push(i);
}
return res;
}
}
博客围绕 LeetCode 085 最大矩形问题展开,指出该题与 84 题是同类问题,解题思路是自己更新每一行的高度数组,然后计算到达当前行的最大面积,还提及会给出代码。
1818

被折叠的 条评论
为什么被折叠?



