第一题:盛最多水的容器
来源:https://leetcode.cn/problems/container-with-most-water/description/
给定一个长度为n的整数数组height。有n条垂线,第i条线的两个端点是(i,0)和(i,height[i])。找出其中的两条线,使得它们与x轴共同构成的容器可以容纳最多的水。返回容器可以储存的最大水量。说明:你不能倾斜容器。
这个题我刚开始想用暴力法,但是题目给到的n的范围是,只通过了部分样例。而且很多组合的面积明显很小,完全没有必要计算,浪费了时间,所以我换成了双指针法。
这个题的难点是要确定核心的计算公式:容器的盛水量 = 两条线中较矮的高度 × 两条线之间的水平距离
主要策略是:(1)初始时,左指针在数组最左端(left=0),右指针在最右端(right=len(height-1));(2)计算当前指针位置的盛水量,并更新最大水量;(3)移动较矮的那个指针,因为移动较高的那个指针不会增加盛水量,只有移动较矮的指针才有可能找到更高的边,从而提高盛水量;(4)终止条件:但左右指针相遇时,遍历结束,返回最大水量。
以下是我的答案:
python
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
max_water = 0
while left < right:
# 计算当前面积
current_width = right - left
current_height = min(height[left], height[right])
current_area = current_width * current_height
# 更新最大水量
if current_area > max_water:
max_water = current_area
# 移动较矮的指针
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_water
模拟一下过程:(height=[1,8,6,2,5,4,8,3,7])
初始left=0,right=8,height[left]=1,height[right]=7,面积8*1=8;
此时height[left] < height[right],移动左指针
第一次移动:left=1,right=8,height[left]=8,height[right]=7,面积7*7=49;
此时height[left] > height[right],移动右指针
第二次移动:left=1,right=7,height[left]=8,height[right]=3,面积6*3=18;
此时height[left] > height[right],移动右指针
第三次移动:left=1,right=6,height[left]=8,height[right]=8,面积5*8=40;
此时height[left] = height[right],随便移动一个,我移动的是右指针
第四次移动:left=1,right=5,height[left]=8,height[right]=4,面积4*4=16;
此时height[left] > height[right],移动右指针
第五次移动:left=1,right=4,height[left]=8,height[right]=5,面积3*5=15;
此时height[left] > height[right],移动右指针
第六次移动:left=1,right=3,height[left]=8,height[right]=2,面积2*2=4;
此时height[left] > height[right],移动右指针
第七次移动:left=1,right=2,height[left]=8,height[right]=6,面积1*6=6;
此时height[left] > height[right],移动右指针
此时left=1,right=1,不满足循环条件,跳出循环。
比较下来,最大面积为49,符合所给样例。
好了,这个题非常清晰易懂,记录完毕。