?????????https://leetcode.com/problems/largest-rectangle-in-histogram/

来源:互联网 发布:淘宝退货时间规定 编辑:程序博客网 时间:2024/05/21 04:25

https://leetcode.com/problems/largest-rectangle-in-histogram/

递归:(然而会超时 而且height很长时迭代深度太高)

1.找最低点 计算最低点*总长的V

2.分为左右两个list 分别再找最低 

3.把所有的V放在list里 找最大的得出答案 

def a(height,list):    if height==[]:        return 0    min=height[0]    minindex=0        for i in range(len(height)):        if height[i]<min:            minindex = i            min = height[i]    vol=min*len(height)    list.append(vol)        leftlist=height[0:minindex]    if minindex!=len(height)-1:        rightlist=height[minindex+1:]    else:        rightlist=[]        a(leftlist,list)    a(rightlist,list)def largestRectangleArea(height):    list=[]    a(height,list)    max=0    for i in list:        if i>max:            max=i    return max

一般方法 遍历每个点 找以这个点为高的最大面积 

向左右找到比它小的截止 中间的宽度即可 然而依然超时

def largestRectangleArea(height):    max=0    #height.append(0)    #height.insert(0,0)    length=len(height)    for i in range(length):        vol=0        for j in range(i)[::-1]:            if height[j]<height[i]:                vol=vol+height[i]*(i-j-1)                break            else:                if height[j]>=height[i] and j==0:                    vol=vol+height[i]*(i-1)        for j in range(i,length):            if height[j]<height[i]:                vol=vol+height[i]*(j-i)                break            else:                if height[j]>=height[i] and j==length:                    vol=vol+height[i]*(length-i)        if vol>max:            max=vol    return max
?????????最后是discuss的答案 看了很久没看懂 特别简洁

class Solution:    # @param {integer[]} height    # @return {integer}    def largestRectangleArea(self,height):        if height==[]:            return 0        max=height[0]        height.append(0)        for i in range(len(height)):            j=i-1            while j>=0 and height[j]>height[i]:                vol=height[j]*(i-j)                if vol>max:                    max=vol                height[j] = height[i]                j=j-1                        return max   
?????????????还有堆栈的做法



0 0
原创粉丝点击