LeetCode刷题记143
85. 最大矩形
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return 0;
int[] heights = new int[matrix[0].length];
int ans = 0;
for (int i = 0; i < matrix.length; i ++) {
for (int j = 0; j < matrix[i].length; j ++) {
if (i == 0 && matrix[i][j] == '1') {
heights[j] = 1;
} else if (matrix[i][j] == '1') {
heights[j] += 1;
} else {
heights[j] = 0;
}
}
ans = Math.max(ans, largestRectangleArea(heights));
}
return ans;
}
public int largestRectangleArea(int[] heights) {
int[][] ind = new int[heights.length][2];
Stack<Integer> sta = new Stack<Integer>();
for (int i = 0; i < heights.length; i ++) {
ind[i][1] = heights.length;
while (sta.isEmpty() == false) {
if (heights[sta.peek()] >= heights[i]) {
ind[sta.peek()][1] = i;
sta.pop();
} else break;
}
if (sta.isEmpty() == false) ind[i][0] = sta.peek();
else ind[i][0] = -1;
sta.push(i);
}
int ans = 0;
for (int i = 0; i < heights.length; i ++) {
ans = Math.max(ans, heights[i] * (ind[i][1] - ind[i][0] - 1));
}
return ans;
}
}
我又偷懒,用了前一题的代码,我除了吃,什么都不会,好难受,要加油呀。
3/3
143/150
————————————再做一次的分割线————————————————
class Solution {
public int maximalRectangle(char[][] matrix) {
int n = matrix.length;
if (n == 0) return 0;
int m = matrix[0].length;
int[][] a = new int[n][m]; //记录横向扫描
int[][] b = new int[n][m]; //记录竖向扫描
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (matrix[i][j] == '1') {
a[i][j] = b[i][j] = 1;
if (j > 0 && matrix[i][j - 1] == '1') {
a[i][j] += a[i][j - 1];
}
if (i > 0 && matrix[i - 1][j] == '1') {
b[i][j] += b[i - 1][j];
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (a[i][j] != 0 && b[i][j] != 0) {
int tmp = b[i][j];
int _min = a[i][j];
for (int k = i; k > i - b[i][j]; k --) {
_min = Math.min(_min, a[k][j]);
if (_min * b[i][j] < ans) break;
ans = Math.max(ans, (b[i][j] - (-- tmp)) * _min);
}
}
}
}
return ans;
}
}