题目描述
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
问题分析
如下图所示,可以参考柱状图面积求解方法计算最大面积

解题方法1
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int res = 0;
vector<int> height;
for (int i = 0; i < matrix.size(); ++i) {
height.resize(matrix[i].size());//再处理下一组数据之前将保存每组柱状图各个柱子高度的数组重新设置大小。
for (int j = 0; j < matrix[i].size(); ++j) {
height[j] = matrix[i][j] == '0' ? 0 : (1 + height[j]);
}
res = max(res, largestRectangleArea(height));
}
return res;
}
int largestRectangleArea(vector<int>& heights) {
if(heights.empty())
return 0;
stack<int> st;
heights.push_back(0);
int res0=0;
for(int i=0;i<heights.size();i++){
while(!st.empty()&&heights[i]<heights[st.top()]){
int curHeight = heights[st.top()];
st.pop();
int width = st.empty()? i : i - st.top() - 1;
if(width*curHeight>res0)
res0=width*curHeight;
}
st.push(i); //单调栈中放的是下标 而不是高度
}
return res0;
}
};
网友评论