题目链接:maximal-rectangle
import java.util.Arrays; /** * Given a 2D binary matrix filled with 0's and 1's, * find the largest rectangle containing all ones and return its area. * */ public class MaximalRectangle { // 65 / 65 test cases passed. // Status: Accepted // Runtime: 292 ms // Submitted: 0 minutes ago //时间复杂度O(n ^ 2), 空间复杂度 O(n) public int maximalRectangle(char[][] matrix) { if(matrix.length == 0) { return 0; } int m = matrix.length; int n = matrix[0].length; int[] H = new int[n]; int[] L = new int[n]; int[] R = new int[n]; Arrays.fill(H, 0); Arrays.fill(L, 0); Arrays.fill(R, n); int ret = 0; for(int i = 0; i < m; ++i) { int left = 0; int right = n; for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { ++H[j]; L[j] = Math.max(L[j], left); } else { left = j + 1; H[j] = 0; L[j] = 0; R[j] = n; } } for (int j = n - 1; j >= 0; j --) { if (matrix[i][j] == '1') { R[j] = Math.min(R[j], right); ret = Math.max(ret, H[j] * (R[j] - L[j])); } else { right = j; } } } return ret; } }
给定一个矩阵,里面只包含‘0’和‘1’,求出给最大的正方形的边长,该正方形里面全是‘1’
public int maximalRectangle1(char[][] matrix) { if(matrix.length == 0) { return 0; } int m = matrix.length; int n = matrix[0].length; int[] H = new int[n]; int[] L = new int[n]; int[] R = new int[n]; Arrays.fill(H, 0); Arrays.fill(L, 0); Arrays.fill(R, n); int maxLen = 0; for(int i = 0; i < m; ++i) { int left = 0; int right = n; for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { ++H[j]; L[j] = Math.max(L[j], left); } else { left = j + 1; H[j] = 0; L[j] = 0; R[j] = n; } } for (int j = n - 1; j >= 0; j --) { if (matrix[i][j] == '1') { R[j] = Math.min(R[j], right); maxLen = Math.max(maxLen, Math.min(H[j], R[j] - L[j])); } else { right = j; } } } return maxLen; }
[LeetCode 85] Maximal Rectangle (华为2015机试)
原文地址:http://blog.csdn.net/ever223/article/details/45008667