1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
public class { public int maximalRectangle (char[][] matrix) { if (matrix.length == 0) return 0; int column = matrix[0].length, row = matrix.length; int max = 0; int[][] numOfOne = new int[row][column]; for (int i = 0; i < row; ++i) { int[] heights = new int[column]; for (int j = 0; j < column; ++j) { if (matrix[i][j] == '0') numOfOne[i][j] = 0; else numOfOne[i][j] = i > 0 ? numOfOne[i - 1][j] + 1 : 1; heights[j] = numOfOne[i][j]; } max = Math.max(largestRectangleArea(heights), max); } return max; }
public int largestRectangleArea (int[] heights) { int max = 0; for (int i = 0; i < heights.length; ++i) { int index = heights[i]; int l = i, r = i; while (l >= 0 && heights[l] >= index) --l; while (r < heights.length && heights[r] >= index) ++r; int area = heights[i] * (r - l + 1 - 2); max = Math.max(area, max); } return max; }
public static void main (String[] args) { char[][] nums = new char[][]{ {'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'} }; new leetcode85().maximalRectangle(nums); } }
|
近期评论