[leetcode]@python 84. Largest Rectangle in Histogram
2016-02-03 13:56
736 查看
题目链接
https://leetcode.com/problems/largest-rectangle-in-histogram/题目原文
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 heights = [2,1,5,6,2,3],
return 10.
题目大意
给定一个包含小矩形高度的数组,返回这些小矩形覆盖区域的最大矩形的面积解题思路
Actually, we can decrease the complexity by using stack to keep track of the height and start indexes. Compare the current height with previous one.
Case 1: current > previous (top of height stack)
Push current height and index as candidate rectangle start position.
Case 2: current = previous
Ignore.
Case 3: current < previous
Need keep popping out previous heights, and compute the candidate rectangle with height and width (current index - previous index). Push the height and index to stacks.
http://www.cnblogs.com/zuoyuan/p/3783993.html
代码
class Solution(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ stack = [] i = 0 area = 0 while i < len(heights): if stack == [] or heights[i] > heights[stack[len(stack) - 1]]: stack.append(i) else: cur = stack.pop() if stack == []: width = i else: width = i - stack[len(stack) - 1] - 1 area = max(area, width * heights[cur]) i -= 1 i += 1 while stack != []: cur = stack.pop() if stack == []: width = i else: width = len(heights) - stack[len(stack) - 1] - 1 area = max(area, width * heights[cur]) return area
相关文章推荐
- Fatal error in launcher
- [leetcode]@python 83. Remove Duplicates from Sorted List
- python 笔记 break
- python 笔记 break
- Python 连接 Mysql 操作异常
- Python第四讲类、对象和函数
- Python 程序员都会喜欢的6个程序库
- Python实现浏览器自动化操作
- python 正则表达式处理不规范json
- python开发环境搭建
- 【python】如何在类方法前添加装饰器
- Python:os.path路径操作
- python调用java 登陆weblogic
- python 笔记 装饰器
- python 笔记 装饰器
- windows下面安装Python和pip终极教程
- IndentationError: unindent does not match any outer indentation level(Python你是猪头吗?)
- python 中文乱码 问题深入分析
- python------对于面向对象的理解
- Python多线程