leetcode | 最大装水量问题 | python

来源:互联网 发布:电脑主题壁纸软件 编辑:程序博客网 时间:2024/05/01 04:40

问题如下:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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),每次只移动高度较小的指针。

原创粉丝点击