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.
这题可以说,就是有一系列的坐标点(i,ai),选取任意两个点做与x轴垂直的线段,与x轴围成的最大的容积
假设有两点(x,ax)与(y,ay)且y>=x,找到ax与ay中的最小值,然后乘上(y-x)
然后找到其最大面积
面积公式为area = min(ax,ay)*(y-x)
解法:
可以暴力的对所有的点两两匹配后计算其面积
但是时间复杂度为o(n^2)
但是没必要,因为其中有很多不必要的操作
可以左侧一个从0开始移动的点left,右侧一个从结尾开始移动的点right
然后向中心靠拢,
当hight[left]>hight[right]时,right--
当hight[right]>hight[left]时,left++
计算其面积,当left>right时就结束
1 class Solution(object): 2 def maxArea(self, height): 3 """ 4 :type height: List[int] 5 :rtype: int 6 """ 7 l = 0 8 r = len(height)-1 9 maxarea = 0 10 while(l<r): 11 maxarea =max(maxarea,min(height[r],height[l])*(r-l)) 12 if(height[r]>height[l]): 13 l+=1 14 else: 15 r-=1 16 return maxarea
参考资料:
https://leetcode.com/problems/container-with-most-water/solution/
浙公网安备 33010602011771号