题目描述:
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
代码:
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
if len(height) < 2:
return None
res = 0
lo, hi = 0, len(height)-1
while lo < hi:
res = max(res, min(height[lo],height[hi])*(hi-lo))
if height[lo] < height[hi]:
k = lo
while k < hi and height[k] <= height[lo]: # 这里必须是小于等于号,
k += 1
lo = k
else:
k = hi
while k > lo and height[k] <= height[hi]: # 否则会引起死循环
k -= 1
hi = k
return res
思路分析:
参见: https://blog.csdn.net/a83610312/article/details/8548519
时间复杂度:
网友评论