给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] 输出: 6
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack <int> increased_stack;
int area=0;
for(int i=0;i<heights.size();i++)
{
while(!increased_stack.empty()&&heights[i]<heights[increased_stack.top()])
{
int top_tmp=increased_stack.top();
increased_stack.pop();
int start;
if(increased_stack.empty())start=-1;
else start=increased_stack.top();
area=area<(heights[top_tmp]*(i-start-1))?(heights[top_tmp]*(i-start-1)):area;
}
increased_stack.push(i);
}
return area;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size()==0)return 0;
vector<int> tmp(matrix[0].size()+1,0);
int area=0;
for(int i=0;i<matrix.size();i++)
{
for(int j=0;j<matrix[i].size();j++)
{
if(matrix[i][j]=='0')tmp[j]=0;
else tmp[j]=tmp[j]+1;
}
int tmp_area=largestRectangleArea(tmp);
area=area<tmp_area?tmp_area:area;
}
return area;
}
};
执行用时 : 48 ms, 在Maximal Rectangle的C++提交中击败了37.09% 的用户
内存消耗 : 11.5 MB, 在Maximal Rectangle的C++提交中击败了58.18% 的用户