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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
"""
第一次:运行时间超出限制,但感觉没错。
基本思想:双层嵌套循环,外层循环依次遍历列表中的每个元素item1,找出除该元素外,大于等于该元素的其它元素item2,并用tmp临时列表保存两者间的索引差值的绝对值,item1与最大索引差值绝对值之积为item1对应的最大容器值,保存在result中,最后返回result中最大值即为多求。注意,当item1是列表中最大元素,且没有与它相等的item2时,此时tmp为空,使用max函数会报错,在这种情况下,可忽略。
"""
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ result = [] for index1, item1 in enumerate(height): tmp = [] for index2, item2 in enumerate(height): if index1 != index2 and item2 >= item1: tmp.append(abs(index1-index2)) if tmp: result.append(max(tmp) * item1) else: continue return max(result)
"""
Time Limit Exceeded
"""
"""
第二次:参考网上的暴力解法,发现自己第一次写的代码太啰嗦。简化如下,但是运行仍然超出时间限制
"""
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ maxarea, area = 0, 0 for i in range(len(height)): for j in range(i + 1, len(height)): maxarea = max(maxarea, min(height[i], height[j]) * (j - i)) return maxarea
"""
Time Limit Exceeded
"""
"""
第三次:参考网上的双指针解法:i指向开始位置,j指向结束位置,每次比较i和j位置的值大小,计算当前面积,同时将值较小的向较大的方向前移一位,更新最大面积。
为什么这么做呢?这样可以只对数据扫描一遍;面积为较短边与宽度(两边的索引之差)的乘积,高度固定情况下,宽度越大,面积越大,如果每次移动的是值较大的一边,那么计算出的面积还是较短边与宽度的乘积,且相比之前的面积更小了。但是如果移动的是值较小的一边,虽然宽度减小了,但可能高度会变大,面积不一定减小。
"""
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ i, j = 0, len(height) - 1 area, maxarea = 0, 0 while i < j: if height[i] < height[j]: area = height[i] * (j - i) i += 1 else: area = height[j] * (j - i) j -= 1 maxarea = max(area, maxarea) return maxarea
"""
Runtime: 108 ms, faster than 43.41% of Python online submissions forContainer With Most Water.
Memory Usage: 13.2 MB, less than 5.21% of Python online submissions forContainer With Most Water.
"""