Leetcode 85. Maximal Rectangle

来源:互联网 发布:in java.library.path 编辑:程序博客网 时间:2024/06/15 21:49

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 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 6.


    public int maximalRectangle(char[][] matrix) {        if (matrix.length == 0 || matrix[0].length == 0) return 0;        int row = matrix.length;        int col = matrix[0].length;        int max = 0;        int[] height = new int[col];                for (int i = 0; i < row; i++) {            for (int j = 0; j < col; j++) {                height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;            }            max = Math.max(max, maxArea(height));        }        return max;            }        private int maxArea(int[] heights) {        int res = 0;        Stack<Integer> s = new Stack<>();        int len = heights.length;        for (int i = 0; i <= len; i++) {            int h = (i == len ? 0 : heights[i]);            if (s.isEmpty() || h >= heights[s.peek()]) s.push(i);            else {                int temp = s.pop();                res = Math.max(res, heights[temp] * (s.isEmpty() ? i : i - 1 - s.peek()));                i--;            }        }        return res;    }




public int maximalRectangle(char[][] matrix) {        if (matrix.length == 0 || matrix[0].length == 0) return 0;        int row = matrix.length;        int col = matrix[0].length;        int max = 0;                int[] height = new int[col];        int[] left = new int[col];        int[] right = new int[col];        Arrays.fill(right, col);                for (int i = 0; i < row; i++) {            int cur_left = 0, cur_right = col;            // height            for (int j = 0; j < col; j++) {                height[j] = matrix[i][j] == '1' ? height[j] + 1 : 0;            }                        for (int j = 0; j < col; j++) {                left[j] = matrix[i][j] == '1' ? Math.max(left[j], cur_left) : 0;                cur_left = matrix[i][j] == '1' ? cur_left : j + 1;            }                        for(int j = col - 1; j >= 0; --j) {                right[j] = matrix[i][j] == '1' ? Math.min(right[j], cur_right) : col;                cur_right = matrix[i][j] == '1' ? cur_right : j;            }                          for(int j = 0; j < col; ++ j) {                max = Math.max(max, (right[j] - left[j]) * height[j]);             }        }                return max;


原创粉丝点击