class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty())
{
return 0;
}
int row = matrix.size();
int col = matrix.at(0).size();
vector<int> heights(col , 0);
int maxArea = INT_MIN;
int area;
//计算以当前行及其向上的直方图的高度
for(int i = 0 ; i < row ; i++)
{
for(int j = 0 ; j < col ; j++)
{
if('0' == matrix.at(i).at(j))
{
heights.at(j) = 0;
}
else if('1' == matrix.at(i).at(j))
{
heights.at(j)++;
}
}
//计算当前行及其向上部分的直方图的面积
area = largestRectangleArea(heights);
maxArea = max(area , maxArea);
}
return maxArea;
}
//求最大矩形高度,用栈维护一个单调非递减区间的下标;当前元素 >= 栈顶对应高度, 将当前元素下标压入栈;
//一旦遇到当前元素大于栈顶元素,则计算以栈顶高度为最小值的矩阵的最大面积,面积 = 栈顶对应高度 * (终点 - 起点 + 1)
//终点=当前元素对应位置 - 1 , 起点=弹出栈顶后的新栈顶位置+1;不断弹出栈顶,直到当前元素 >= 栈顶对应高度
int largestRectangleArea(vector<int>& heights)
{
if(heights.empty())
{
return 0;
}
int size = heights.size();
stack<int> hists;
int i = 0;
int top;
int width;
int area = INT_MIN;
while(i < size)
{
if(hists.empty() || heights.at(i) >= heights.at( hists.top() ))
{
hists.push(i++);
}
//需要计算最大面积
else
{
top = hists.top();
hists.pop();
width = hists.empty() ? i : (i - 1 - hists.top());
area = max(area , heights.at(top) * width);
}
}
//将最后元素再做一次计算
while(!hists.empty())
{
top = hists.top();
hists.pop();
width = hists.empty() ? i : (i - 1 - hists.top());
area = max(area , heights.at(top) * width);
}
return area;
}
};
leecode 解题总结:85. Maximal Rectangle
最新推荐文章于 2020-11-02 15:37:56 发布