LeetCode- Add to List 84. Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
代码中有几点注意:
1.height末尾要自己push_back个值为0的元素;
2.出栈后,栈是否为空影响面积的计算,具体是影响长方形的长;
3.栈顶的元素出栈后,若height[i]仍小于height[s.top()],则继续出栈。
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
if(height.size()==0) return 0;
int res=0;
stack<int> s;
height.push_back(0);
for(int i=0;i<height.size();++i){
if(s.empty()||(!s.empty()&&height[s.top()]<=height[i]))
s.push(i);
else{
while(!s.empty()&&height[s.top()]>height[i]){
int width=s.top();
s.pop();
int length=(s.empty()?i:i-s.top()-1);
int area=height[width]*length;
res=max(res,area);
}
s.push(i);
}
}
return res;
}
};
2017-12-4更新
在官网上看到一个链接讲解的很详细,参考他的想法又重新又Java实现了一遍。
1.建立一个空栈来存放数组下标
2.从头开始遍历数组
2.1如果栈为空或者当前数组值大于等于栈顶元素对应的高度值,则将这个数组下标入栈
2.2如果当前数组值小于栈顶元素对应的高度值,则将栈中元素一直出栈直到栈顶元素小于或等于高度值,计算当前长方形面积,长方形的高就是出栈元素的高度值,而长方形的宽是当前数组下标-当前栈顶元素-1
3.遍历完后,如果栈不空,则按照2.2的方法将元素出栈并计算面积值
Java实现
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> s=new Stack<>();
int maxArea=0;
int currentMaxArea=0;
int tp=0;
int i=0;
while(i<heights.length)
{
if(s.empty()||heights[s.peek()]<=heights[i])
{
s.push(i++);
}
else
{
tp=s.peek();
s.pop();
currentMaxArea=heights[tp]*(s.empty()?i:(i-s.peek()-1));
if(currentMaxArea>maxArea)
maxArea=currentMaxArea;
}
}
while(!s.empty())
{
tp=s.peek();
s.pop();
currentMaxArea=heights[tp]*(s.empty()?i:(i-s.peek()-1));
if(currentMaxArea>maxArea)
maxArea=currentMaxArea;
}
return maxArea;
}
}