python【力扣LeetCode算法题库】11-盛最多水的容器

11. 盛最多水的容器
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

在这里插入图片描述
示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49
思路

依旧是双指针法,一个放在开头,一个放在结尾,面积就是两个索引中较短的长度*双指针之间的距离,每次更新显然是要把较短的那端向另一头移动,这样较有可能使得面积更大

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        l = 0 
        r = len(height) - 1
        s = 0
        while l < r:
            s = max( (r-l)*min(height[l], height[r]), s)
            if height[l] > height[r]:
                r -= 1
            else:
                l += 1
        return s
发布了695 篇原创文章 · 获赞 199 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_43838785/article/details/104544248