问题描述
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.
例子
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
2016-06-03
暴力求解
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
area = 0
for i in range(len(height)):
for j in range(i+1,len(height)):
tmp = min(height[j],height[i])*(j-i)
area = max(area,tmp)
return area
S = Solution()
height = [1,8,6,2,5,4,8,3,7]
S.maxArea(height)
效率分析
利用python这种暴力求解的解法没有通过。
Status: Time Limit Exceeded
有没有其他办法???
在刚才的过程中,如果起始点固定为A,我们期望如果后面出现的数小于A,那么我们希望它尽可能的的靠近A。如果后面出现的数大于A,那么则希望它尽可能的远。这样分析,刚才的计算过程中就有两种情况的计算是无意义的:
- 定点为A,后面的小于A,越靠近的计算越不必要。
- 顶点为A,后面有大于A的,越靠近的计算也是无意义的。
双指针
left,right = 0,len(height)-1
area = 0
while(left<right):
tmp = min(height[left],height[right])*(right-left)
area = max(area,tmp)
if height[left]>=height[right]:
right = right -1
else : left = left +1
# print(area)
return area
效率分析
Runtime: 108 ms, faster than 54.84% of Python online submissions for Container With Most Water.
Memory Usage: 13 MB, less than 72.65% of Python online submissions for Container With Most Water.