LeetCode 85. Maximal Rectangle(java)

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
思路:这道题其实是 LeetCode 84. Largest Rectangle in Histogram(java)的变形,只是这里从一维数组变成二维数组,因此,我们的策略就是逐行扫描,每一行都计算一次largest rectangle in histogram,因此我们需要用一个height[]数组来保存逐行扫描的histogram的结果,每行都调用一次largest rectangle in histogram的代码,最后maintain一个最大值即可。
class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
        int row = matrix.length;
        int col = matrix[0].length;
        int[] height = new int[col + 1];
        height[col] = 0;
        int maxArea = 0;
        for (int i = 0; i < row; i++) {
            Stack<Integer> stack = new Stack<>();
            for (int j = 0; j <= col; j++) {
                if (j == col) {
                    height[j] = 0;
                } else if (matrix[i][j] == '1') {
                    height[j] += 1;
                } else {
                    height[j] = 0;
                }
                if (stack.isEmpty() || height[j] >= height[stack.peek()]) {
                    stack.push(j);
                } else {
                    while (!stack.isEmpty() && height[j] < height[stack.peek()]) {
                        int temp = stack.pop(), len = 0;
                        if (stack.isEmpty()) len = j;
                        else len = j - 1 - stack.peek();
                        maxArea = Math.max(maxArea, height[temp] * len);
                    }
                    //注意这里不能再用j--,而要用stack.push(j),不然15行的height[j]++就要再加一次,会影响结果。
                    stack.push(j);
                }
            }
        }
        return maxArea;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值