LeetCode: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.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

给出一串整数,a1, a2, …, an ,以(i,ai)为点到x轴做垂线。在这些线中,找出两条线,使得他们围成的矩形面积最大。
暴力求解法很简单,但时间不通过,所以这里不说了。然后想了一个提高性能的方法,是这样的:保存当前位置之前最高点那个位置,只要遍历那个最高点位置左侧所有的点(因为最高点在这,右侧只会越来越小),与当前位置所围成的最大面积就是要求的结果。但是时间还是通不过。只能看答案了。
思路:Two Pointer Approach
上面也提到了,这个题目的要求包含了两店重要的潜在说明。第一,组成矩形区域的高由短的那条线决定;第二,距离越远,组成的矩形面积越大。
基于这两点,考虑这样的一个算法:从左右两侧开始遍历,取两端的线围成矩形区域,然后去除短的那一根,并从那个位置向另一端移动,这样每次都可以保证最远距离,高度最大,从而围成的面积最大。然后取遍历过程中的最大值即可。这样的时间复杂度只有O(n)。
class Solution:
def maxArea(self, height: List[int]) -> int:
l = len(height)
p = [0 for i in range(l)]
maxHeight = 0
maxHeightIndex = 0
maxArea = 0
left = 0
right = l-1
maxArea = (right-left) * min(height[left],height[right])
while (left < right):
if height[left] < height[right]:
left+=1
else:
right-=1
# 记录最大值
maxArea = max(maxArea,(right-left) * min(height[left],height[right]))
return maxArea
THE END.
308

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



