85. Maximal Rectangle

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了85. Maximal Rectangle相关的知识,希望对你有一定的参考价值。

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
class Solution {
    public int maximalRectangle(char[][] matrix) {
        int le = matrix.length;
        int res = 0;
        if(le == 0) return 0;
        ArrayList<Integer> li = new ArrayList();
        for(int i = 0; i < matrix[0].length; i++) li.add(0);
        for(int i = 0; i < le; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] == ‘0‘) li.set(j, 0);
                else li.set(j, li.get(j)+1);
            }
            int tmp = maxhisto(li);
            res = Math.max(tmp, res);
        }

            return res;
    }
    public int maxhisto(ArrayList<Integer> list){
        int res = 0;
        int s = list.size();
        for(int i = 0; i < s; i++){
            if(i+1 < s && list.get(i+1)>=list.get(i)) continue;
            int mh = list.get(i);
            for(int j = i; j >= 0; j--){
                mh = Math.min(mh, list.get(j));
                int area = mh * (i - j + 1);
                res = Math.max(area, res);
            }
        }
        return res;
    }
}

把每一列看成histogram,就可以得到4个histogram,从第一行开始,0,01,012,0123.把数值存入arraylist,如果是1就在原基础上+1,如果是0就置0.

然后用求maxhistogram里的方法,最简单的方法就是找局部顶点(数值大于右边)然后从局部顶点向左计算area面积。

以上是关于85. Maximal Rectangle的主要内容,如果未能解决你的问题,请参考以下文章

85. Maximal Rectangle

85. Maximal Rectangle

85. Maximal Rectangle

85. Maximal Rectangle

85.Maximal Rectangle

85. Maximal Rectangle