84. Largest Rectangle in Histogram
思路:
如果当前元素比栈顶元素大,进栈
否则,计算站里元素组成的最大面积,再将站里元素全部换为当前元素(小一点)
最后站里都是递增的,然后按照面积挨个算
class Solution {
public:
int largestRectangleArea(vector<int>& height)
{
int result = 0;
stack<int> stk;
for(int i = 0; i < height.size(); i++)
{
if (stk.empty() || stk.top() <= height[i])
stk.push(height[i]);
else
{
int count = 0;
while (!stk.empty() && stk.top() > height[i])
{
count++;
result = max(result, stk.top() * count);
stk.pop();
}
while (count--)
stk.push(height[i]);
stk.push(height[i]);
}
}
int count = 1;
while ( !stk.empty() )
{
result = max(result, stk.top() * count);
count ++;
stk.pop();
}
return result;
}
};
85. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
way-1:
这道题跟最大子矩阵的思想比较类似,都是降一维(减少变量数量)转化成简单问题
指定任意一行作为矩形的下边界,那么问题就变成了求直方图的最大面积的矩形,参见之前的这篇文章。
所以思路就是,从上到下,依次求直方图最大面积矩形,感觉瞬间没有难度了。下面的代码里,第一个函数就是原封不动搬过来的。。
class Solution {
public:
int largestRectangleArea(vector<int>& height)
{
int result=0;
stack<int> stk;
for(int i=0;i<height.size();i++)
{
if(stk.empty() || stk.top()<=height[i])
stk.push(height[i]);
else
{
int count=0;
while(!stk.empty() && stk.top()>height[i])
{
count++;
result=max(result,stk.top()*count);
stk.pop();
}
while(count--)
stk.push(height[i]);
stk.push(height[i]);
}
}
int count=1;
while(!stk.empty())
{
result=max(result,stk.top()*count);
count++;
stk.pop();
}
return result;
}
int maximalRectangle(vector<vector<char>>& matrix)
{
if (matrix.empty() || matrix[0].empty())
return 0;
int maxArea = 0;
int row = matrix.size();
int col = matrix[0].size();
vector<int> histo(col + 1, 0); // 在末尾增加一个0起收割作用
for (int i = 0; i < row; i++)
{
// 计算直方图
for (int j = 0; j < col; j++)
histo[j] = (histo[j] + 1) * (matrix[i][j] - '0'); //求直方图这个地方也很巧妙
maxArea = max(maxArea, largestRectangleArea(histo));
}
return maxArea;
}
};