阅读 84

LeetCode最大矩形

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

示例:

输入: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] 输出: 6

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ma…

解题思路

  1. 通过题解里看到这个图就一目了然。和柱状图中最大的矩形是一样的思路。
  2. 将二维数组转换成数组传入max方法。返回最后的面积。
public int maximalRectangle(char[][] matrix) {
    if(matrix.length == 0) {
        return 0;
    }
    int[] heights = new int[matrix[0].length];
    
    int max = 0;
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length; j++) {
            if(matrix[i][j] == '1') {
                heights[j] += 1;
            } else {
                heights[j] = 0;
            }
        }
        max = Math.max(max, max(heights));
    }
    return max;
}

public int max(int[] heights) {
    Stack<Integer> stack = new Stack<>();
    stack.push(-1);
    int max = 0;
    for (int i = 0; i < heights.length; i++) {
        while (stack.peek() != -1 && heights[stack.peek()] >= heights[i]) {
            max = Math.max(max, heights[stack.pop()] * (i - stack.peek() - 1));
        }
        stack.push(i);
    }
    while (stack.peek() != -1) {
            max = Math.max(max, heights[stack.pop()] * (heights.length - stack.peek() - 1));
    }
    return max;
}
复制代码
关注下面的标签,发现更多相似文章
评论