您的位置:首页 > 职场人生

[LeetCode] Largest Rectangle in Histogram

2014-01-04 06:14 375 查看
问题:

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
.
分析:
比较难的一道题。我们构建一个stack来保存indexes。从前向后,一个一个往里推。推的时候,如果新来的一个柱形大于等于stack中顶端的柱形,那么我们就直接推;如果新来的柱形小于stack顶端的柱形,那么就稍微麻烦一点了,我们需要一直pop stack,直到顶端的柱形小于等于新的柱形。在pop的过程中,每一次pop,我们都更新一次result。这样做的结果就是:stack里的柱形永远都保持上升。每次一遇到要下降的,就更新一次前面的。还有就是,如果stack.top的柱形跟新来的柱形不是挨着的(因为之前pop过),那么top的举行永远比pop出去那些矮。

代码:(O(n))

class Solution {
public:
int largestRectangleArea(vector<int> &h) {
stack<int> s;
int result = 0;
h.push_back(0);
int i = 0;
while (i < h.size()) {
if (s.empty() || h[s.top()] <= h[i]) s.push(i++);
else {
int temp = s.top();
s.pop();
if (s.empty()) result = max(result, h[temp] * i);
else result = max(result, h[temp] * (i - s.top() - 1));
}
}
return result;
}
};


想再仔细分析一下10~15行的代码。12行结束之后,我们有三个值:s.top()(简称top), temp和 i。他们之间的关系是:top < temp < i 。两两之间可以挨着也可以不挨着。如果都挨着,不用多说,因为i-top-1就是1。分析不挨着的情况:top和temp之间的柱形为什么没了呢?那是因为他们都比temp大;temp和 i 之间柱形为什么都没了呢?因为他们都比 i 大,但同时他们也比temp大,因为如果他们比temp小,那早在它们还是新来的时候,temp就应该已经被pop掉了。所以,所有空缺的位置都比temp大,所以我们有h[temp]
* (i - s.top() - 1)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 面试 leetcode