盛最多水的容器

55 阅读1分钟

1. 题目

leetcode.cn/problems/co…

image.png

2. 解析

使用双指针,如果我们移动数字较大的那个指针,那么前者「两个指针指向的数字中较小值」不会增加,后者「指针之间的距离」会减小,那么这个乘积会减小。因此,我们移动数字较大的那个指针是不合理的。因此,我们移动 数字较小的那个指针。

3. 核心代码

class Solution(object):
    def maxArea(self, height: List[int]) -> int:
        l = 0
        r = len(height) - 1
        res = 0
        max_height = max(height)
        while l < r:
            res = max(res, min(height[l], height[r]) * (r - l))
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
            # 对结果进行剪枝减少循环步骤,当前结果大于该段中的所有数据,就结束循环
            if res >= max_height * (r - l): break
        return res