这是一类题,其核心就是牢牢把握住“短板”二字
谁白了这就是木桶效应,能放水的高度是由那个短板决定的
方法都是相同的即大体思路就是:
首先需要两个指针,分别从左右出发,然后比较两者,哪个低我们就取哪一个作为当前能放水的最大高度,依次来进行一系列相关的计算
下面先来看第一个例子
正如上面所说,这里定义左右两个指针,当然了这里并非真真的指针,他们的取值就是走过的矩形的最大高度
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