题目描述:https://leetcode-cn.com/problems/container-with-most-water/description/
思路:按照描述,很容易想到,对所有点进行遍历,选择最大的容积,按照这种思路,编写代码:
class Solution:
def maxArea(self, height: List[int]) -> int:
n = len(height)
water_max = 0
for i in range(0,n-1):
for j in range(i+1,n):
h = min(height[i],height[j])
w = j - i
water = h * w
if water > water_max:
water_max = water
return water_max
这里遇到了第一个需要注意的地方:题目中所给的数组是从1开始的,而Python默认是从0开始的,需要调整过来。此外,range(x,y)
函数返回的是从x ~ y-1
的列表。
完成这段代码之后,上传到LeetCode,提示超过时间限制(毕竟算法的时间复杂度为 O(n^2) )。那么考虑对算法进行优化:
class Solution:
def maxArea(self, height: List[int]) -> int:
Area = []
num = int(len(height))
left_num = 0
right_num = num-1
while left_num < right_num:
left_cupwall = height[left_num]
right_cupwall = height[right_num]
area = min(left_cupwall,right_cupwall) * (right_num - left_num)
Area.append(area)
if left_cupwall <= right_cupwall:
left_num += 1
else:
right_num -= 1
max_area = max(Area)
return max_area
通过测试。