题目:给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。
思路:矩形面积最大,比较简单
方案一:两个循环,很容易实现,耗时有点长
class Solution:
def maxArea(self, height: List[int]) -> int:
max_area = 0
temp_area = 0
length = 0
max_length = len(height)
if max_length < 2:
return 0
for i in range(max_length):
for j in range(max_length):
if height[i] <= height[j] :
short_height = height[i]
high_height = height[j]
length = abs(j - i)
temp_area = short_height * length
else:
short_height = height[j]
high_height = height[i]
length = abs(i - j)
temp_area = short_height * length
if temp_area >= max_area:
temp = temp_area
temp_area = max_area
max_area = temp
return max_area
方案二:
class Solution:
def maxArea(self, height: List[int]) -> int:
max_area = 0
temp_area = 0
index1 = 0
index2 = len(height) - 1
while index1 < index2:
if height[index1] <= height[index2]:
short_height = height[index1]
high_height = height[index2]
length = index2 - index1
temp_area = short_height * length
index1 += 1
else:
short_height = height[index2]
high_height = height[index1]
length = index2 - index1
temp_area = short_height * length
index2 -= 1
if temp_area >= max_area:
temp = temp_area
temp_area = max_area
max_area = temp
return max_area