【LeetCode】解题85:Maximal Rectangle

Problem 85: Maximal Rectangle [Hard]

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

Example:

Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6

来源:LeetCode

解题思路

本题需要沿用题解84:Largest Rectangle in Histogram的思想,相当于是对84题的二维扩展。
一个二维矩阵中的最大的全1面积,可以分解为对每一行求一次Largest Rectangle in Histogram,最后对m行结果取最大值。其中每行的histogram是该行的每一列往上能够延伸的最高全1高度。

具体过程:

  • 首先遍历数组,对当前行i求取一个hist,求取公式为:
    h i s t [ j ] = ( h i s t [ j ] + 1 ) ∗ m a t r i x [ i ] [ j ] , j ∈ [ 0 , n − 1 ] hist[j] = (hist[j] + 1) * matrix[i][j], j\in [0, n-1] hist[j]=(hist[j]+1)matrix[i][j],j[0,n1]
    意义是对上一行的hist[j]累计1,若当前值matrix[i][j]是0时则清零。其中n为数组的列数。
  • 然后对i行的hist求Largest Rectangle in Histogram,这里使用栈的方法,具体过程见题解84:Largest Rectangle in Histogram.
  • 使用返回的area更新最大面积maxArea。

整个算法遍历了m行,每行使用一次Largest Rectangle in Histogram计算复杂度为 O ( n ) O(n) O(n),因此最终的时间复杂度为 O ( m n ) O(mn) O(mn)

Solution (Java)

class Solution {
    int m, n;
    public int maximalRectangle(char[][] matrix) {
        m = matrix.length;
        if(m == 0) return 0;
        n = matrix[0].length;
        int[] hist = new int[n];
        int area, maxArea = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                hist[j] = (hist[j] + 1) * Integer.parseInt(String.valueOf(matrix[i][j]));
            }
            area = largestRect(hist);
            maxArea = Math.max(maxArea, area);
        }
        return maxArea;
    }
    private int largestRect(int[] hist){
        Stack<Integer> sk = new Stack<Integer>();
        sk.push(-1);
        sk.push(0);
        int area, max = 0;
        for(int i = 1; i < n; i++){
            while(i < n && hist[i] >= hist[sk.peek()]){
                sk.push(i);
                i++;
            }
            if(i == n) break;
            while(sk.peek() != -1 && hist[i] <= hist[sk.peek()]){
                area = hist[sk.pop()] * (i - sk.peek() - 1);
                max = Math.max(max, area);
            }
            sk.push(i);
        }
        while(sk.peek() != -1){
            area = hist[sk.pop()] * (n - sk.peek() - 1);
            max = Math.max(max, area);
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值