标签:for containe size 两个指针 point color container least nbsp
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.
分析:
方法一:使用最简单的嵌套循环遍历,找出每一种组合。但此方法超时
方法二:容器的盛水量取决于两块板中的最短板,所以两个指针,一头一尾,记录其盛水量,然后向中间移动其较短的板,期间记录最大盛水量,直至两个指针相遇。这样时间复杂度就由方法一的O(N2)变为了O(N)。使用两个指针,一头一尾的方法很值得借鉴。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
n = len(height)
i = 0
j = n-1
max_area = 0
while(i<j):
if height[i] < height[j]:
area = (j-i)*height[i]
i += 1
else:
area = (j-i)*height[j]
j -= 1
if area > max_area:
max_area = area
return max_area
标签:for containe size 两个指针 point color container least nbsp
原文地址:http://www.cnblogs.com/Peyton-Li/p/7736463.html