42 Trapping Rain Water And 11. Container With Most Water

这是一类题,其核心就是牢牢把握住“短板”二字

谁白了这就是木桶效应,能放水的高度是由那个短板决定的

方法都是相同的即大体思路就是:

首先需要两个指针,分别从左右出发,然后比较两者,哪个低我们就取哪一个作为当前能放水的最大高度,依次来进行一系列相关的计算

下面先来看第一个例子

正如上面所说,这里定义左右两个指针,当然了这里并非真真的指针,他们的取值就是走过的矩形的最大高度

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        leftmax = 0
        rightmax = 0
        i = 0
        j = len(height)-1
        result = 0
        while i<j:
            leftmax = max(height[i],leftmax)
            rightmax = max(height[j],rightmax)
            if leftmax<rightmax:
                result+=leftmax-height[i]
                i+=1
            else:
                result+=rightmax-height[j]
                j-=1
        return result

同理下面这道题也是一样的思路,要定义左右两个指针,只不过不同的就是在具体相关计算上面要随着题意的变化而作相应的变化。

给一下代码吧

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        leftmax = 0
        rightmax = 0
        i = 0
        j = len(height)-1
        result = 0
        while i<j:
            leftmax = max(height[i],leftmax)
            rightmax = max(height[j],rightmax)
            if leftmax<rightmax:
                result=max(result,leftmax*(j-i))
                i+=1
            else:
                result=max(result,rightmax*(j-i))
                j-=1
        return result

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值