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.
谷歌翻译拉过来:
给定n个非负整数a1,a2,...,an,其中每个代表坐标(i,ai)处的一个点。 绘制n条垂直线,使得线i的两个端点处于(i,ai)和(i,0)处。 找到两条线,它们与x轴一起形成一个容器,使得容器包含最多的水。
注意:不倾斜容器,n至少为2。
思路:暴力的方法求出所有值,再一一比较,这样时间复杂度过高,是O(n^2)。首先,乘水量是由短线段决定的 ,所以就是|i2-i1|*min{ai1,ai2}。我们定义两个指针,指向这一列数的首尾,用该公式求得结果,和存储的最大面积作比较,更新最大值。若左边比右边短,则更新左边界,左++。否则,若右边短,右--。该方法的时间复杂度是O(n)
1 class Solution(object): 2 def maxArea(self, height): 3 size = len(height) 4 maxm = 0 5 j = 0 6 k = size - 1 7 while j < k: 8 if height[j] <= height[k]: 9 maxm = max(maxm,height[j] * (k - j)) 10 j += 1 11 else: 12 maxm = max(maxm,height[k] * (k - j)) 13 k -= 1 14 return maxm 15 if __name__=='__main__': 16 height = [1,4,2,6,8,4] 17 solution = Solution() 18 print(solution.maxArea(height))

浙公网安备 33010602011771号