Largest Rectangle in Histogram(Hard)
Description
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 heights = [2,1,5,6,2,3],
return 10.
analysis
题目所给的函数为int largestRectangleArea(vector& heights),所以给出来的每一个立柱的高度其实是以向量的形式给出的,一开始看到这道题其实是没有思路的,后来发现其实是可以用stack来求解最大面积。
做法是先将第一个立柱的高度入栈,此后如果后一个立柱的高度比前一个立柱高就入栈,否则就出栈,计算所求矩形的面积,如果计算的出来面积比之前记录的最大面积要大则更新面积,直到栈中立柱的高度比当前的立柱高度要低为止,记录当前立柱的横坐标(横坐标入栈)。
注意这道题的一个小关键就是为了最后要使所有的高度都出栈以计算最大的面积,我采取的方法是把0加入到heights的向量中,这样就能保证最后所有的立柱都出栈了。利用heights得到立柱高度,而利用新建栈和当前的立柱横坐标得到底以计算矩形面积。
以下是代码。
Code
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if(heights.size() == 0) return 0;
vector<int> vec;
heights.push_back(0);
int result = 0;
//int num = 0;
for(int i = 0 ;i<heights.size();++i){
//if(vec.size() == 0) vec.push_back(i);
//else{
while(vec.size()>0 && heights[vec.back()] >= heights[i]){
int h = heights[vec.back()];
vec.pop_back();
int bottom ;
if(vec.size()==0) bottom = i;
else bottom = i-vec.back()-1;
if(h*bottom > result) result = h*bottom;
}
vec.push_back(i);
//}
}
return result;
}
};