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
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @   依嘫  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示