您的位置:首页 > 其它

Leetcode: Largest Rectangle in Histogram

2014-12-12 20:34 239 查看
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
.

分析:这道题解法参考,leetcode.pdf, 解法很巧妙。该题思想的入手点跟Container with Most Water类似,高度最矮的那个柱子决定矩形的面积,所以我们可以按每个柱子为中心向两侧扩展知道遇到比该柱子矮的柱子,但时间复杂度是O(n^2),超时。

改进方法也是上面的思想,但它利用栈很好的维护了上面方法中以一个柱子为最小高度的矩形的左右界,从而将时间复杂度降为O(n)。还有一个trick是将height最后多加一个0,便于处理height只有一个元素和元素全是递增的情况。代码如下:

class Solution {
public:
int largestRectangleArea(vector<int> &height) {
stack<int> S;
height.push_back(0);
int result = 0;

for(int i = 0; i < height.size();){
if(S.empty() || height[i] > height[S.top()])
S.push(i++);
else{
int tmp = S.top();
S.pop();
result = max(result, height[tmp]*(S.empty()?i:i-S.top()-1));
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: