[Leetcode]Largest Rectangle in Histogram
2015-03-14 03:27
381 查看
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 =
The largest rectangle is shown in the shaded area, which has area =
For example,
Given height =
return
有一种很直观的解法,从每一个bar往两边走,以自己的高度为标准,直到两边低于自己的高度为止,然后用自己的高度乘以两边走的宽度得到矩阵面积,更新最大矩阵面积~这种解法时间复杂度为O(n^2),自己写了一遍,但是TLE了~
还有一种优化的算法,只需要扫描一遍,所以复杂度为O(n)~ 可以参考http://blog.csdn.net/linhuanmars/article/details/20524507
class Solution:
# @param height, a list of integer
# @return an integer
def largestRectangleArea(self, height):
if height is None or len(height) == 0: return 0
maxArea = 0; stack = []
height.append(0)
for i in xrange(len(height)):
while stack and height[i] < height[stack[-1]]:
h = height[stack.pop()]
width = i if not stack else i - stack[-1] - 1
maxArea = max(maxArea, h * width)
stack.append(i)
return maxArea
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 =
10unit.
For example,
Given height =
[2,1,5,6,2,3],
return
10.
有一种很直观的解法,从每一个bar往两边走,以自己的高度为标准,直到两边低于自己的高度为止,然后用自己的高度乘以两边走的宽度得到矩阵面积,更新最大矩阵面积~这种解法时间复杂度为O(n^2),自己写了一遍,但是TLE了~
还有一种优化的算法,只需要扫描一遍,所以复杂度为O(n)~ 可以参考http://blog.csdn.net/linhuanmars/article/details/20524507
class Solution:
# @param height, a list of integer
# @return an integer
def largestRectangleArea(self, height):
if height is None or len(height) == 0: return 0
maxArea = 0; stack = []
height.append(0)
for i in xrange(len(height)):
while stack and height[i] < height[stack[-1]]:
h = height[stack.pop()]
width = i if not stack else i - stack[-1] - 1
maxArea = max(maxArea, h * width)
stack.append(i)
return maxArea
相关文章推荐
- [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