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.
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 height = [2,1,5,6,2,3]
,
return 10
.
分析:
方法一:将每一个直方柱进行左右扩展,当遇到比自己矮是就不能扩展,此时计算面积。复杂度为O(N^2),超时。
class Solution { public: int largestRectangleArea(vector<int> &height) { int max_area=0; for(int i=0;i<height.size();i++) { int left=i-1,right=i+1; while(left>=0 && height[left--]>=height[i]); while(right<height.size() && height[right++]>=height[i]); int area=(++left)+(right--); max_area=max(max_area,area); } return max_area; } };
方法二:采用栈来处理。发现高的立柱当一遇到比自己矮的立柱时,就“失效”了。那么越高的立柱“失效”越快。这样我们用一“栈'来存储立柱高度及其坐标。当新的立柱比栈顶”高度“高时,入栈存储(并不计算面积)。当新的立柱高度比栈顶低时,就一直出栈,直到比新立柱低。此时,每一个立柱出栈时,其下标与当前新立柱下标的差之就是该高度维持的”宽度“,求面积。同时,将新立柱入栈,但是下标值应该变为最后出栈的那个立柱的下标,表示此”高度“从那时已经维持了。最后,遍历结束后,将栈中剩余的立柱都逐个出栈,计算面积。复杂度为O(N)
class Solution { public: int largestRectangleArea(vector<int> &height) { stack<pair<int,int> > st; //first存储高度,second存储此”高度“最先出现的位置 st.push(make_pair(-1,-1)); //为了简化判断栈空的情况 int max_area=0,area=0; int n=height.size(); for(int i=0;i<n;i++){ if(height[i]>=st.top().first){ st.push(make_pair(height[i],i)); }else{ int tmp,ind; while(st.top().first>=height[i]){ tmp=st.top().first; ind=st.top().second; area=tmp*(i-ind); max_area=max(max_area,area); st.pop(); } st.push(make_pair(height[i],ind)); } } //将所有栈剩余的都弹出 while(st.top().first!=-1){ int tmp=st.top().first; int ind=st.top().second; area=tmp*(n-ind); max_area=max(max_area,area); st.pop(); } return max_area; } };