leetcode 85. 最大矩形

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
[“1”,”0”,”1”,”0”,”0”],
[“1”,”0”,”1”,”1”,”1”],
[“1”,”1”,”1”,”1”,”1”],
[“1”,”0”,”0”,”1”,”0”]
]
输出: 6

对矩形每行利用单调栈(递增).

  第一行:     ["1","0","1","0","0"],

  第二行:     ["1","0","1","0","0"],
             ["1","0","1","1","1"],

以此类推。

其实就是这道题的升级版: 传送门

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0||matrix[0].length==0){
            return 0;
        }
        int[] h=new int[matrix[0].length];
        int n=matrix.length;
        int m=matrix[0].length;
        int ans=0;
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                h[j]=matrix[i][j]=='0'?0:h[j]+1;
            }
            ans=Math.max(ans,solve(h));
        }
        return ans;
    }

    static class pos{
        int l,r,index,h;
    }

    public int solve(int[] h){
        Stack<pos> st=new Stack<pos>();
        pos[] t=new pos[h.length];
        for(int i=0;i<h.length;++i){
            t[i]=new pos();
            t[i].l=i;
            t[i].index=i;
            t[i].h=h[i];
        }
        for(int i=0;i<h.length;++i){
            while (!st.isEmpty()&&st.peek().h>t[i].h){
                t[st.peek().index].r=i;
                t[i].l=st.peek().l;
                st.pop();
            }
            st.push(t[i]);
        }
        while (!st.isEmpty()){
            t[st.pop().index].r=h.length;
        }
        int ans=0;
        for(int i=0;i<h.length;++i){
            ans=Math.max(ans,(t[i].r-t[i].l)*t[i].h);
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值