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.

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.

一刷
题解:
解题思路


根据上图,可以清楚的看出本题可以转化为Largest Rectangle in Histogarm来做
初始化height = [0, 0 ,0 ....]
对于每一行,先求出以这一行为x轴的每个柱子的高度,求解时,可以每次基于上一行的值进行更新。然后O(n)的时间求出最大矩形,不断更新全局变量res
时间复杂度为 O(n * (n + n)) = O(n2)

public class Solution {
    public int maximalRectangle(char[][] matrix) {
       if(matrix == null || matrix.length == 0) return 0;
       
       int colNum = matrix[0].length;
       int[] accumulatedHeights = new int[colNum];
       int max = 0;
       for(char[] row : matrix){
           for(int i=0; i<colNum; i++){
               //the accumulated, consecutive number of 1
                accumulatedHeights[i] = row[i] == '0' ? 0 : accumulatedHeights[i] + 1;
           }
           max = Math.max(calcLargestHist(accumulatedHeights), max);
       }
       return max;
    }
    
    private int calcLargestHist(int[] heights){
         if(heights == null || heights.length == 0) return 0;
        Stack<Integer> stack = new Stack<Integer>();//store the index
        int max = 0;
        for(int i=0; i<=heights.length; i++){
            int curt = (i == heights.length)? -1: heights[i];//guaranteen the stack is ascending
            while(!stack.isEmpty() && curt<=heights[stack.peek()]){
                int h = heights[stack.pop()];
                int w = stack.isEmpty()? i: i - stack.peek() - 1;
                max = Math.max(max, h*w);
            }
            stack.push(i);
        }
        
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 世界的精彩之处在于每个人都是丰富独立的个体,我们不断变化和成长着。但是总有发现我们做很多事情都彰显着我们的内在性格...
    山水之滴阅读 17,708评论 0 2
  • 一,为什么想起来要练习普通话? 工作和自身素质让自己要学说好普通话。 自己工作常常要对人讲话,自己家乡一直平...
    晚间一壶茶阅读 1,620评论 2 1
  • 今天的想和大家分享一个关于情感关系的小tip🤗 我和小舟属于异地(准确说是异国)~不在一起的时候会十分想念对方,特...
    蛋糕小屋阅读 239评论 0 0
  • 思想的巨人,行动的矮子 我妹总说我是思想的巨人,行动的矮子。哈哈,有时候觉得挺搞笑的,发现身边的人会比自己更了解自...
    1朵云阅读 305评论 10 3