这个需要O(n3),所以没有通过大集合的测试。
leetcode的讨论组给出了一个比较难理解的方法,这里就不采用了。
说说第三个方法。前一个笔记,我们讨论了柱状图的最大矩形面积,那可以O(n)的,学以致用呀!btw,leetcode的这两题也是挨一块儿的,用心良苦。。。。
如果我们把每一行看成x坐标,那高度就是从那一行开始往上数的1的个数。带入我们的maxAreaInHist方法,在O(n2)时间内就可以求出每一行形成的“柱状图”的最大矩形面积了。它们之中最大的,就是我们要的答案。
这里有一个和leetcode相关的细节。就是本来在计算height数组的时候,我们没有必要分配成代码中的那个样子,一维就可以了,然后在遍历每一行的时候计算当前行的height数组,然后再计算maxArea。这种情况下还是过不了大集合,所以不得不为每一行都保存一个height,先期计算该二维数组。
public class Solution {
// 套用 Largest Rectangle in Histogram 的算法
// 计算 预处理之后每一行对应的柱状图的最大值
public static int largestRectangleArea(int[][] heights, int row) {
Stack<Integer> stack = new Stack<Integer>();
int max = 0;
for (int i = 0; i <= heights[row].length; i++) {
int curt = (i == heights[row].length) ? -1 : heights[row][i];
while (!stack.isEmpty() && curt <= heights[row][stack.peek()]) {
int h = heights[row][stack.pop()];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(max, h * w);
}
stack.push(i);
}
return max;
}
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
// calculate height at each row
// 每一行视为一个柱状图,柱状图的高度,就是从当前这个位置向上数上去,有几个1
int[][] heightTable = new int [m][n];
// initialize the first row
for (int i = 0; i < n; i++) {
if (matrix[0][i] == '0') {
heightTable[0][i] = 0;
} else {
heightTable[0][i] = 1;
}
}
// calculate heights for rest row
for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
heightTable[i][j] = 1 + heightTable[i - 1][j];
} else {
heightTable[i][j] = 0;
}
}
}
int max = 0;
for (int i = 0; i < m; i++) {
int curt = largestRectangleArea(heightTable, i);
max = Math.max(max, curt);
}
return max;
}
}