11.盛最多水的容器
题目
给你n个非负整数a1,a2,.....,an
,每个数代表坐标中的一个点(i,ai)
。在坐标内话n调垂先,垂线两端点分别为(i,ai)
和(i,0)
。找出其中的两条线,使得它们与x轴共同构成的容器可容纳最多的水。
示例:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
输入:height = [1,1]
输出:1
我一开始的思路是,元素之间还是宽,元素本身的值是高度,那么通过指针遍历,找到最优的组合,然而当我写完之后,发现超时。
class Solution:
def maxArea(self, height: List[int]) -> int:
# 元素之间还是宽,元素本身的值是高度
if len(height)<=1:return 0;
start,end=0,len(height)-1
result=0
while(start<end):
width=end-start+1
if height[start]>height[end]:
if width*int(height[start])>result:
result=width*int(height[start])
end-=1
continue
if height[start]<height[end]:
if width*int(height[end])>result:
result=width*int(height[end])
start+=1
continue
return result
后来排查后发现是if width*int(height[start])>result后面不应该加continue,而且这陷入死循环的最大原因是如果不大于result的话,那么就不会移动指针,那么循环就会一直持续下去。
这是正确的答案
class Solution:
def maxArea(self, height: List[int]) -> int:
# 元素之间还是宽,元素本身的值是高度
if len(height)<=1:return 0;
start,end=0,len(height)-1
max_area=0
while start<end:
area=(end-start)*min(height[start],height[end])
max_area=max(max_area,area)
if height[start]<height[end]:
start+=1
else:
end-=1
return max_area
测试用例:
def maxArea(height):
# 元素之间还是宽,元素本身的值是高度
if len(height)<=1:return 0;
start,end=0,len(height)-1
max_area=0
while start<end:
area=(end-start)*min(height[start],height[end])
max_area=max(max_area,area)
if height[start]<height[end]:
start+=1
else:
end-=1
return max_area
s=[1,8,6,2,5,4,8,3,7]
print(maxArea(s))