LeetCode Notes_#11 Container with Most Water
Contents
题目
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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
思路和解答
思路
乍一看没太好的思路,没有一个固定的规律,还是要经过一些计算和比较的。那么问题在于如何减少计算比较的次数呢?
解答
class Solution(object):
def maxArea(self, height):
""" :type height: List[int] :rtype: int """
i,j=0,len(height)-1#定义两个指针去遍历height数组
res=0
while(i<j):#终止条件是两个指针相等,相当于在中间相遇
res=max(res,min(height[i],height[j])*(j-i))#更新最大值
if height[i]>height[j]:
j=j-1
else:
i=i+1
return res
需要注意的点
- 循环语句要用while,不要用for,因为循环的次数不是确定的,而是根据i,j的大小去决定
- 每次循环只移动一个指针,并且移动的是高度较小那一侧的指针,理由:
- 首先不可能一次就同时移动两边的指针,会漏过一些可能的最大值
- 其次如果移动高度较高的一侧的指针,那么也有可能错过最大值