题目描述
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
被这题虐的不轻快,感觉贪心也不总是那么简单的。我的思路是硬暴力求解,四重循环,着实垃圾。
题解区大神的思路,参考leetcode Largest Rectangle in Histogram
博客链接:最大直方图面积 这道题博主讲的很详细。。还画了图
这道题就是利用一个记忆数组h,如果第n层二维数组中元素为1且第n-1层也为1,则逐层累加;
如果中间有一层出现了0断裂,则重新计算。
然后每层做一次求直方图的最大面积。最后就能计算出来了。
我也画个图吧,免得以后忘了思路,只能感概大神都太强。
遍历第一行时数组为1010111011,可以求出最大直方图为红框内的值。
第二行:2020220102,可以发现第二层为0的值把上一层的值都断开了,再次求最大直方图面积为紫色框。
第三行:0131331010,第三层求最大直方图面积为蓝色框,全部遍历完毕,返回即可。
import java.util.*;
public class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int m = matrix.length;
int n = matrix[0].length;
int [] h = new int [n + 1];
int res = 0;
for(int i = 0; i < m; ++i){
Stack<Integer> stack = new Stack<Integer> ();
for(int k = 0; k < n; ++k){
if(matrix[i][k] == '1'){
++h[k];
}else{
h[k] = 0;
}
}
int k = 0;
while(k < n + 1){
if(stack.isEmpty() || h[stack.peek()] <= h[k]){
stack.push(k++);
}else{
int height = stack.pop();
res = Math.max(res, (stack.isEmpty()?k:(k - 1 - stack.peek()))*h[height]);
}
}
}
return res;
}
}