【LeetCode】 85. Maximal Rectangle 最大矩形(Hard)(JAVA)
题目地址: https://leetcode.com/problems/maximal-rectangle/
题目描述:
Given a rows x cols binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = []
Output: 0
Example 3:
Input: matrix = [["0"]]
Output: 0
Example 4:
Input: matrix = [["1"]]
Output: 1
Example 5:
Input: matrix = [["0","0"]]
Output: 0
Constraints:
- rows == matrix.length
- cols == matrix.length
- 0 <= row, cols <= 200
- matrix[i][j] is ‘0’ or ‘1’.
题目大意
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
解题方法
这道题其实是可以变成上一题:【LeetCode】 84. Largest Rectangle in Histogram 柱状图中最大的矩形(Hard)(JAVA)
-
计算当前行 1 的高度,遇到 0 位置
-
计算当前行的最大矩形
-
note,84 题解法:1、求出左侧和右侧比当前元素小的第一个位置;2、求出当前元素的面积
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 max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == '0') {
heights[j] = 0;
} else {
heights[j]++;
}
}
max = Math.max(max, mH(heights));
}
return max;
}
public int mH(int[] heights) {
int[] left = new int[heights.length];
int[] right = new int[heights.length];
for (int i = 0; i < heights.length; i++) {
int next = i - 1;
while (next >= 0 && heights[i] <= heights[next]) {
next = left[next] - 1;
}
left[i] = next + 1;
}
for (int i = heights.length - 1; i >= 0; i--) {
int next = i + 1;
while (next < heights.length && heights[i] <= heights[next]) {
next = right[next] + 1;
}
right[i] = next - 1;
}
int max = 0;
for (int i = 0; i < heights.length; i++) {
max = Math.max(max, (right[i] - left[i] + 1) * heights[i]);
}
return max;
}
}
执行耗时:4 ms,击败了92.47% 的Java用户
内存消耗:41.1 MB,击败了86.40% 的Java用户