leetcode 85. 最大矩形

520 阅读1分钟
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。


输入:

 [

 ["1","0","1","0","0"], 

 ["1","0","1","1","1"],

 ["1","1","1","1","1"],

 ["1","0","0","1","0"] 

输出: 6  


此题可以转换为 84. 柱状图中最大的矩形  (leetcode)

image.png


对于二维数组的行或列进行遍历,转换位求每行的连续一所组成的高度数组能组成的最大矩阵面积



代码:

    public int largestRectangleArea(int[] heights) {
        if(heights==null||heights.length<=0)
            return 0;
        Stack<Integer> stack = new Stack<>();
        int reuslt = 0;
        for(int i=0;i<heights.length;++i){
            if(stack.isEmpty()||heights[stack.peek()]<=heights[i]){
                stack.add(i);
            }
            else{
                while (!stack.isEmpty()&&heights[stack.peek()]>heights[i]) {
                    int k = stack.pop();
                    int left = stack.isEmpty() ? -1 : stack.peek();
                    int right = i;
                    reuslt = Integer.max(reuslt, (k - left + right - k - 1) * heights[k]);
                }
                stack.add(i);
            }
        }
        while (!stack.isEmpty()){
            int k = stack.pop();
            int left = stack.isEmpty() ? -1 : stack.peek();
            int right = heights.length;
            reuslt = Integer.max(reuslt, (k - left + right - k - 1) * heights[k]);
        }
        return reuslt;
    }






    public int maximalRectangle(char[][] matrix) {
        if(matrix==null||matrix.length<=0)
            return 0;
        int[] nu =  new int[matrix[0].length];
        int result = 0;
        for(int i=0;i<matrix.length;++i){
            for(int k=0;k<nu.length;++k){
                if(matrix[i][k]=='1')
                    nu[k] += 1;
                else
                    nu[k] = 0;
            }
            result = Integer.max(result,largestRectangleArea(nu));
        }
        return result;
    }