LeetCode 11

本文介绍了解决LeetCode11题目的方法,题目要求找出能存储最多水的两个线段组合。通过双指针法,从两端逐步逼近,记录每次计算得到的最大水量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 11. Container With Most Water

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.

解题思路

由题意,要求给定多个容器中能够容纳水的最大量。设定指针first, last分别表示高度的最前端和最后端,在指针每一次移动过程中,都计算当前能够存储的水量,并与之前算得的最大存储量相比较,更新最大存水量。由于容器的体积由较小的边界决定,故求解过程中将高度定义为有效高度,并且如果更新后的容器高度比原来高度低,则求得的存水量必然没有之前的最大存水量大,所以当出现这种情况时,指针继续前移或后移,直到出现更大的容器高度。

示意图

源代码

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        water = 0
        first = 0
        last = len(height) - 1
        while first < last:
            h = min(height[first], height[last])
            water = max(water, (last - first) * h)
            while height[first] <= h and first < last:
                first += 1
            while height[last] <= h and first < last:
                last -= 1
        return water
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值