[Leetcode][python]Largest Rectangle in Histogram

来源:互联网 发布:常用的数据分析模型 编辑:程序博客网 时间:2024/06/03 16:58

题目大意

给定一个柱状图,求它能包含的最大的矩形的面积。如下图中阴影部分就是要求的矩形。
这里写图片描述

解题思路

栈,难题。
看了半天两个解法,只有下图最容易理解:
http://www.cnblogs.com/zuoyuan/p/3783993.html
https://shenjie1993.gitbooks.io/leetcode-python/084%20Largest%20Rectangle%20in%20Histogram.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:  # 不递增开始弹栈                curr=stack.pop()                if stack == []:                    width = i                 else:                    width = i-stack[len(stack)-1]-1                area=max(area,width*heights[curr])                i-=1            i+=1        while stack != []:            curr = stack.pop()            if stack == []:                width = i             else:                width = len(heights)-stack[len(stack)-1]-1            area = max(area,width*heights[curr])        return area

总结

stack.pop()输出弹出的值

原创粉丝点击