Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] Output: 6
找出二维数组中能用1围成的最大长方形,并返回面积
该题可以扩展为题64 求数组int[]中能组成的最大矩形面积,当前位置为0时 代表数组中矩形长度为0 否则代表长度+1;
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix==null || matrix.length==0 ||matrix[0].length==0) {
return 0;
}
int res=0;
int height[] = new int[matrix[0].length] ;
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++) {
height[j]=matrix[i][j]=='1'? height[j]+1:0;
}
res = Math.max(res, largestRectangleArea(height));
}
return res;
}
public int largestRectangleArea(int[] heights) {
int max = 0;
for (int i = 0; i < heights.length; i++) {
// 调过非波峰值的结果
if (i + 1 < heights.length && heights[i] <= heights[i + 1]) {
continue;
}
int height = heights[i];
for (int j = i; j >= 0; j--) {
height = Math.min(height, heights[j]);
max = Math.max(max, height * (i - j + 1));
}
}
return max;
}
}