LeetCode-085-最大矩形

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;    
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值