LeetCode-【数组】-柱状图中最大的矩形&最大矩形

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zw159357/article/details/81253894

1.柱状图中最大的矩形

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]

图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

示例:

输入: [2,1,5,6,2,3]
输出: 10

题目分析:http://chuansong.me/n/390896436960

class Solution {
    public int largestRectangleArea(int[] heights) {
        if(heights==null||heights.length==0)
            return 0;
        Stack<Integer> res=new Stack<>();
        int i=0;
        int maxValue=0;
        for(;i<heights.length;i++){
            if(res.empty()||heights[res.peek()]<=heights[i])
                res.push(i);
            else{
                int top=res.pop();
                int index=res.empty()?-1:res.peek();
                maxValue=Math.max(maxValue,heights[top]*(i-1-index));
                i--;
            }
        }
        while(!res.empty()){
            int top=res.pop();
            int index=res.empty()?-1:res.peek();
            maxValue=Math.max(maxValue,heights[top]*(i-1-index));
        }
        return maxValue;
    }
}

2.最大矩形

给定一个仅包含 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的个数当成矩形的高,就变成了上面的问题。

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix.length == 0)return 0;
        int m=matrix.length;
        int n=matrix[0].length;
        int[] h=new int[n+1];
        h[n]=0;
        int maxValue=0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][j]=='1')
                    h[j]++;
                else
                    h[j]=0;
            }
            Stack<Integer> res=new Stack<>();
            for(int j=0;j<=n;j++){
                if(res.isEmpty()||h[res.peek()]<=h[j])
                    res.push(j);
                else{
                    while(!res.isEmpty()&&h[j]<h[res.peek()])
                        maxValue=Math.max(maxValue,h[res.pop()]*(res.isEmpty()?j:(j-1-res.peek())));
                    res.push(j);
                }
            }
        }
        return maxValue;
    }
}

猜你喜欢

转载自blog.csdn.net/zw159357/article/details/81253894
今日推荐