MENU

LeetCode85. 最大矩形

August 13, 2018 • Read: 3276 • LeetCode阅读设置

题目链接:LeetCode85

题解

这是LeetCode84题的一个扩展。这道题做法和84很类似,首先对第一行求一个最大体积,然后到第二行,将第一行的值累加到第二行上,但是有一个前提条件,如果第二行某一列的值是0,那就直接是0了,比方说第二行累加后的值为2,0,2,1,1,然后对这个值求一次最大体积。第三行累加后的值为3,1,3,2,2,第四行累加后的值为4,0,0,3,0

代码
class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int maxArea = 0;
        int[] height = new int[matrix[0].length];
        for(int i = 0;i < matrix.length;i++) {
            for(int j = 0;j < matrix[0].length;j++) {
                height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;
            }
            maxArea = Math.max(maxArea,largestRectangleArea(height));
        }
        return maxArea;
    }
    public static int largestRectangleArea(int[] heights) {
        if(heights == null || heights.length == 0)
            return 0;
        int maxArea = 0;
        Stack<Integer> stack = new Stack<Integer>();//从栈底到栈顶依次增大
        for(int i = 0;i < heights.length;i++) {//遍历数组
            while(!stack.isEmpty() && heights[i] <= heights[stack.peek()]) {
                //栈不为空并且当前值小于等于栈顶元素
                int j = stack.pop();//出栈
                int k = stack.isEmpty() ? -1 : stack.peek();
                int curArea = (i - k - 1) * heights[j];//底×高
                maxArea = Math.max(maxArea,curArea);//找最大值
            }
            stack.push(i);//i进栈
        }
        while(!stack.isEmpty()) {
            //数组遍历完了,栈内还有值
            int j = stack.pop();
            int k = stack.isEmpty() ? -1 : stack.peek();
            int curArea = (heights.length - k - 1) * heights[j];
            maxArea = Math.max(maxArea,curArea);
        }
        return maxArea;
    }
}
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code