11. Container 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.
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
"""
n = len(height)
if n == 2:
return min(height)
left = 0
right = n - 1
maxArea = min(height[0], height[n-1])*(n-1)
while(right > left):
if(height[left]<=height[right]):
left += 1
else:
right -= 1
curArea = min(height[left], height[right]) * (right-left)
if(curArea > maxArea):
maxArea = curArea
return maxArea
开始的时候思路出了一点错误,以为只要找到一个最大和次大的数值的然后由内向外循环排除能够找到,问题是没有考虑可能最优区间内并不全部包含最大和次大的数值,此时应该是底下的index对Area的贡献最高。
其实双指针这个方法就是当index影响很大的时候如果把数组的x,y坐标交换,从外向内遍历的一种妥协吧。
本文详细解析了如何解决经典的容器盛水问题,通过双指针算法寻找两直线间能容纳的最大水量,给出了清晰的实现思路与代码示例。


被折叠的 条评论
为什么被折叠?



