题目:11. Contaier With Most Water
题目要求:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
算法思路:从坐标轴的左右两端开始,因为,左右两端的x轴距离最大,相对而言,所能包含的面积更大。采用迭代法,一次一次的记录最大的面积。
设左边高度给height[l],右边高度为height[r],其中,r为右边的索引号,l为左边的索引号,每次迭代,记录(r - l) * max(height[r],height[l]), 即记录下所能存储的最大水量,记为max,同时,保持height[r],height[l]中较高的一方,然后将较低的一方的索引号向另一方索引号靠近。
比如:
if height[l] < height[r]:
l += 1
else:
r -= 1
循环往复,知道l==r,这样记录下来的最大面积即为题目所求的最大面积。
算法正确性:
该算法类似于贪心算法,每次迭代都是选择当前x轴距离的最大面积,并且保留较高的“一块木板”, 然后去寻找另一个更高的木板,比较彼此之间的“储水量”(面积),在重复计算比较之后,选择出来的最大面积就是正确的答案。
代码展示:
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxarea = 0 //最大面积初始为0
r = len(height) - 1 //右边索引号
l = 0 //左边索引号while(l<r):
h = min(height[l], height[r]) //储水量由最矮木板觉得
maxarea = max(maxarea, (r - l) * h ) //比较当前储水量是不是比上
一个最大储水量大
if height[l] < height[r]: //保留高的那块‘木板’
l += 1
else:
r -= 1
return maxarea
代码结果: