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.
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram.png)
Above is a histogram where width of each bar is 1, given height =
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram_area.png)
The largest rectangle is shown in the shaded area, which has area =
For example,
Given height =
return
分析:这道题解法参考,leetcode.pdf, 解法很巧妙。该题思想的入手点跟Container with Most Water类似,高度最矮的那个柱子决定矩形的面积,所以我们可以按每个柱子为中心向两侧扩展知道遇到比该柱子矮的柱子,但时间复杂度是O(n^2),超时。
改进方法也是上面的思想,但它利用栈很好的维护了上面方法中以一个柱子为最小高度的矩形的左右界,从而将时间复杂度降为O(n)。还有一个trick是将height最后多加一个0,便于处理height只有一个元素和元素全是递增的情况。代码如下:
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram.png)
Above is a histogram where width of each bar is 1, given height =
[2,1,5,6,2,3].
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram_area.png)
The largest rectangle is shown in the shaded area, which has area =
10unit.
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; } };
相关文章推荐
- [LeetCode] Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram 解题报告
- LeetCode —— Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram(直方图最大面积)
- LeetCode-Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram
- leetcode-084:Largest Rectangle in Histogram
- LeetCode 笔记系列 17 Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram、Maximal Rectangle
- [leetcode]Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram
- [leetcode] Largest Rectangle in Histogram
- [leetcode]Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram(直方图最大面积)
- leetcode之Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- leetcode - Largest Rectangle in Histogram
- leetcode -- Largest Rectangle in Histogram TODO O(N)
- LeetCode Online Judge 题目C# 练习 - Largest Rectangle in Histogram