码迷,mamicode.com
首页 > 其他好文 > 详细

85. Maximal Rectangle

时间:2019-10-10 09:14:03      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:style   mat   solution   col   for   fill   res   ==   put   

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

标签:style   mat   solution   col   for   fill   res   ==   put   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11645722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!