您的位置:首页 > 编程语言 > Python开发

leetcode | 最大装水量问题 | python

2017-05-31 19:58 411 查看
问题如下:

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.
给出一个数组,每个元素表示水桶高度,水桶的最终高度由数组中的两个元素组成(由两者较小的高度决定,短板效应),水桶的宽度由两个元素的下标差决定,求最大装水量。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
j = len(height)-1
water = 0
while i<j:
water = max(water,(j-i)*min(height[i],height[j]))
if height[i]<height[j]:
i+=1
else:
j-=1
return water其中i,j等同于数组的指针,算法的时间复杂度 O(n),每次只移动高度较小的指针。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: