class Solution {
//first O(n^2)TLE: enumerate every bar i, look for the nearest left bar smaller than bar i, and nearest right bar smaller than bar i
//second O(n):using an stack to keep record of the height and width, the key observation: if h[j]<h[i](j>i), then position k(k>j) will never need
//to touch h[i], only need to record the width of j
public:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = 0;
stack<pair<int,int>> s;//record height and width
s.push(make_pair(0, 0));
for (int i = 0; i < height.size()+1; ++i)
{
int curHeight;
if(i < height.size())
curHeight = height[i];
else curHeight = -1;
if(curHeight > s.top().first)//it is higher than the current top height
s.push(make_pair(curHeight, 1));
else
{//if height is smaller than the current top height, than take down all higher stick in stack
//in the meantime we need to calculate the size
int minH = 0x7FFFFFFF;//assign the MAX_INT to min, test data contains the MAX_INT
int sumWidth = 0;
while (!s.empty() && s.top().first >= curHeight)
{
minH = min(minH, s.top().first);
sumWidth += s.top().second;
ans = max(minH*sumWidth, ans);
s.pop();
}
s.push(make_pair(curHeight, sumWidth+1));
}
}
return ans;
}
};
second time
class Solution {
public:
struct Node
{
int h;
int l;
Node(int _h = 0, int _l = 0):h(_h),l(_l){};
};
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<Node> hs;
int maxArea = 0;
for(int i = 0; i < height.size(); ++i)
{
int curH = height[i];
if(hs.empty()) hs.push(Node(curH, 1));
else if(hs.top().h <= curH) hs.push(Node(curH, 1));
else
{
int curL = 0;
int minH = INT_MAX;
while(!hs.empty() && hs.top().h > curH)
{
curL += hs.top().l;
minH = hs.top().h;
maxArea = max(maxArea, curL*minH);
hs.pop();
}
hs.push(Node(curH, 1+curL));
}
}
//
int curL = 0;
int minH;
while(!hs.empty())
{
curL += hs.top().l;
minH = hs.top().h;
maxArea = max(maxArea, curL*minH);
hs.pop();
}
return maxArea;
}
};
本文介绍了一种求解最大矩形面积的高效算法,通过使用栈来记录柱状图的高度和宽度,实现了从O(n^2)到O(n)的时间复杂度优化。文章提供了两种实现方式,包括详细的数据结构定义和关键步骤解析。
906

被折叠的 条评论
为什么被折叠?



