您的位置:首页 > 其它

【LeetCode】Largest Rectangle in Histogram

2014-05-27 00:03 274 查看
题目描述:

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*n)的解法太明显,试都不用试就知道肯定TLE……但是更效率的算法一直想不出来。只好求助于万能的网络,看到大神的解法,真是觉得跟自己不是一个世界的人……什么时候能达到这种水平……
思路是这样的:

对位置为i的元素,能构成的最大矩形:以i为中心向两边延伸,左边界为第一个小于i的数,右边界为第一个小于i的数。如何确定这个位置,从思路上来讲挺困难的。

画图无能,引用下详细解释的外链:Largest Rectangle in Histogram

代码如下:

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