您的位置:首页 > 编程语言 > Python开发

[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 = 
[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
.

有一种很直观的解法,从每一个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 python