地址 https://leetcode.cn/problems/maximal-rectangle/
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
示例 2:
输入:matrix = []
输出:0
示例 3:
输入:matrix = [["0"]]
输出:0
示例 4:
输入:matrix = [["1"]]
输出:1
示例 5:
输入:matrix = [["0","0"]]
输出:0
提示:
rows == matrix.length
cols == matrix[0].length
1 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'
本题解答使用到084 的单调栈代码
或者说就是084的二维加强数据版本
我们逐层扫描,每层使用084的代码记性最大矩形求解。
调用一次单调栈求柱状图矩形的时间复杂度为O(n)
逐层调用 ,共有m层,总的复杂度就是O(nm)
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int len = heights.size();
vector<int> leftmin(len, -1); vector<int> rightmin(len, len);
stack<int> st;
for (int i = 0; i < len; i++) {
while (!st.empty() && heights[i] <= heights[st.top()]) { st.pop(); }
if (!st.empty()) { leftmin[i] = st.top(); }
st.push(i);
}
while (!st.empty()) { st.pop(); }
for (int i = len - 1; i >= 0; i--) {
while (!st.empty() && heights[i] <= heights[st.top()]) { st.pop(); }
if (!st.empty()) { rightmin[i] = st.top(); }
st.push(i);
}
int ans = 0;
for (int i = 0; i < len; i++) {
int left = leftmin[i]; int right = rightmin[i];
ans = max(ans, (right - left - 1) * heights[i]);
}
return ans;
}
int maximalRectangle(vector<vector<char>>& matrix) {
int n = matrix.size(); int m = matrix[0].size();
if (n == 0 || m == 0) return 0;
vector<int> heights(m, 0);
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == '1') { heights[j]++; }
else { heights[j] = 0; }
}
ans = max(ans, largestRectangleArea(heights));
}
return ans;
}
};
标签:matrix,示例,int,085,heights,len,矩形,Leetcode
From: https://www.cnblogs.com/itdef/p/16724747.html