给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入: [1,8,6,2,5,4,8,3,7] 输出: 49
解题思路:
首先,看到这道题的时候,自己解题的思路发生了改变,第一想法没有想到暴力解法。估计是之前练了一个月左右的题,改变自己的思维方式,所以说,多练编程题是很有好处滴,等过一段时间,准备回顾数据结构这一本书。第一想到的是双指针的思路。中间还是调试了几次,才通过测试。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
sum = 0 # 装水总和
length = len(height)
left_index = 0
right_index = length-1
if length ==2:
if height[0] > height[1]:
return height[1]*1
else:
return height[0]
if length >=3:
while True:
if height[left_index] <=height[right_index] and right_index>left_index:
temp = height[left_index]*(right_index-left_index)
if temp>sum:
sum = temp
left_index+=1
elif height[left_index] >height[right_index] and right_index>left_index:
temp = height[right_index]*(abs(left_index-right_index))
if temp>sum:
sum = temp
right_index-=1
else:
break
return sum
50 / 50 个通过测试用例
状态: 通过
执行用时:128 ms
然后,看了下别人的解答,思路差不多,然后重新优化了一下代码,感觉之前的代码比较长。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
length = len(height)
maxArea, left_index, right_index = 0, 0, length - 1
while (left_index < right_index):
maxArea = max(maxArea, min(height[left_index], height[right_index]) * (right_index - left_index))
if height[left_index] < height[right_index]:
left_index += 1
else:
right_index -= 1
return maxArea
50 / 50 个通过测试用例
状态: 通过
执行用时:136 ms