leetcode 85. 最大矩形-java实现

题目所属分类

最大矩形 单调栈

原题链接

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

代码案例:在这里插入图片描述
输入:matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
输出:6
解释:最大矩形如上图所示。

题解

在这里插入图片描述
leetcode 84. 柱状图中最大的矩形-java实现
在这里插入图片描述

 class Solution {
    public int largestRectangleArea(int[] heights) {
            int n = heights.length;
            int[] left = new int[n+1];
            int[] right = new int[n+1];
            Stack<Integer> s = new Stack<>();
            //形成左边界
            for(int i = 0 ; i < heights.length ; i++){
                while(!s.isEmpty() && heights[s.peek()]  >= heights[i]) s.pop();
                if(s.isEmpty()) left[i] = -1 ;
                else left[i] = s.peek();
                s.push(i);
            }
            s.clear();
            //形成右边界
             for(int i = n-1 ; i >= 0 ; i--){
                while(!s.isEmpty() && heights[s.peek()]  >= heights[i]) s.pop();
                if(s.isEmpty()) right[i] = n ;
                else right[i] = s.peek();
                s.push(i);
            }
            //遍历高
            int res = 0 ;
            for(int i = 0 ; i < n ; i++){
                res = Math.max(res,heights[i]*(right[i]-left[i]-1));//存的是范例中1的右边和2的左边
            }
            return res;

    }
    
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length <= 0 || matrix[0].length < 0) return 0;
        int n = matrix.length;
        int m = matrix[0].length;
        int[][] h = new int[n + 10][m + 10];

        for(int i = 0;i < n;i ++)
            for(int j = 0;j < m;j ++)
            {
                if(matrix[i][j] == '1')
                {
                    if(i > 0 ) h[i][j] = 1 + h[i - 1][j]; 
                    else h[i][j] = 1;
                }
            }

        int res = 0;
        for(int i = 0;i < n;i ++) res = Math.max(res,largestRectangleArea(h[i]));

        return res;

 
    }
}

h可以弄成一维的

public int maximalRectangle(char[][] matrix) {
    if (matrix.length == 0 || matrix[0].length == 0) return 0;
    int n = matrix.length, m = matrix[0].length;
    int res = 0;
    int[] h = new int[m];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] == '1') h[j]++;
            else h[j] = 0;
        }
        res = Math.max(res, largestRectangleArea(h));
    }
    return res;
}

作者:pyro
链接:https://www.acwing.com/activity/content/code/content/429486/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

依嘫_吃代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值