1.1 题目描述
1.2 分析
直接利用两重循环,暴力搜索出最大的体积,然后进行输出,进行了提交了,时间超时。然后在阅读答案和其他人员的代码之后,其实比暴力搜索更容易的方式,设立两个指针,一个从头一个从尾,相向而行遍历数组,每次舍弃较短边。
(1)暴力搜索
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max = 0
imax = 0
right = len(height) - 1
while right >0 :
for lelf in range(right):
if(height[lelf] > height[right]):
imax = height[right] * (right - lelf)
else:
imax = height[lelf] * (right - lelf)
if(max < imax):
max = imax
right = right - 1
return max
提交之后
根据其他参阅之后的代码修改
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxs = 0
lelf = 0
right = len(height) -1
while lelf < right:
maxs = max(maxs,min(height[lelf],height[right])*(right - lelf))
if height[lelf] > height[right]:
right = right - 1
else:
lelf = lelf + 1
return maxs