84. Largest Rectangle in Histogram
問題描述:
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
For example,
Given heights = [2,1,5,6,2,3]
,
return 10
.
問題解析:
代碼如下:
class Solution {
public:
// 利用堆棧來解決
int largestRectangleArea(vector<int>& heights)
{
if(heights.empty())
return 0;
stack<int>sta;
int cur = 0, max = 0;
int len = 0;
int size = heights.size();
for(int i=0; i<size; ++i)
{
if(sta.empty() || sta.top() <= heights[i])
sta.push(heights[i]);
else
{
len = 0;
while(!sta.empty() && sta.top() > heights[i])
{
++ len;
cur = sta.top()*len;
if(cur > max) max = cur;
sta.pop();
}
while(len)
{
--len;
sta.push(heights[i]);
}
sta.push(heights[i]);
}
}
while(!sta.empty())
{
++ len;
cur = sta.top()*len;
if(cur > max) max = cur;
sta.pop();
}
return max;
}
};
85. Maximal Rectangle
問題描述:
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 0Return 6.
問題解析:
1. 此題是求矩陣中爲1的最大的矩形元素個數。
2. 此題可以化爲上題中求柱狀圖最大面積。從矩陣第0行開始,每一行可以看成是一個heights數組,本行j位置爲1,如果上一行此列爲1,則heights[j] = height[j]+1,然後求最大矩形面積,利用上題代碼。
代碼如下:
class Solution {
public:
// 利用堆棧求最大的數字
void largestRectangleArea(vector<int>& heights, int &max)
{
if(heights.empty())
return;
stack<int>sta;
int cur = 0;
int len = 0;
int size = heights.size();
for(int i=0; i<size; ++i)
{
if(sta.empty() || sta.top() <= heights[i])
sta.push(heights[i]);
else
{
len = 0;
while(!sta.empty() && sta.top() > heights[i])
{
++ len;
cur = sta.top()*len;
if(cur > max) max = cur;
sta.pop();
}
while(len)
{
--len;
sta.push(heights[i]);
}
sta.push(heights[i]);
}
}
while(!sta.empty())
{
++ len;
cur = sta.top()*len;
if(cur > max) max = cur;
sta.pop();
}
return;
}
int maximalRectangle(vector<vector<char>>& matrix)
{
int m=matrix.size(), n=0;
if(m>0) n=matrix[0].size();
int max = 0;
vector<int> heights(n, 0);
for(int i=0; i<m; ++i)
{
for(int j=0; j<n; ++j)
{
heights[j] = matrix[i][j]=='1'? heights[j]+1 : 0;
}
largestRectangleArea(heights, max);
}
return max;
}
};