您的位置:首页 > 其它

largest rectangle in histogram leetcode

2015-08-22 20:05 260 查看
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
.

思路分析:暴力破解方法应该不需要多说,直接计算每一个元素所能构成的最大矩形面积,并与max比较并记录。

这道题,是看了网上的众多博客之后结合自己的理解来mark一下这个过程(最主要是一遍就解决了,时间复杂度O(n)):

  用到了栈,栈顶元素,跟当前索引是关键:

    入栈:如果栈为空或者栈顶元素(其在直方图中的对应高度)小于等于当前索引(对应高度),这样就使得,栈中的元素(对应高度)是非递减的。这样符合贪心算法的思想,因为若是当前索引(对应高度)大于栈顶元素(对应高度),则继续入栈,因为必然能得到更大的矩形面积,贪心!

    出栈:当前索引(对应高度)<栈顶元素(对应高度),则栈顶元素出栈,并记录下其对应高度,并计算其能对应的最大矩形面积。注意一个关键点:栈顶元素跟当前索引之间的所有元素(对应高度)都大于等于这两个端点对应高度!

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