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

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   
?????????????还有堆栈的做法



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值