算法题:盛最多水的容器

这个题目乍一看就是双指针,没想到官方解答也是双指针,我在官方的基础上优化了一下下,左右两边各一个指针,每次移动短的那一头的时候,不是移动一格,而是找到比短的那一头要长一点的,再进行比较。(本题完整题目附在了最后面)

代码如下:

复制代码
class Solution(object):
    def maxArea(self, height):
        left = 0
        right = len(height) - 1
        max_volume = 0
        while left < right:
            max_volume = max(max_volume, (right - left) * min(height[left], height[right]))
            if height[left] >= height[right]:
                value = height[right]
                right = right - 1
                while right > left and height[right] < value:
                    right -= 1
            elif height[left] < height[right]:
                value = height[left]
                left = left + 1
                while left < right and height[left] < value:
                    left += 1

        return max_volume


if __name__ == '__main__':
    sol = Solution()
    print(sol.maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]))

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

**说明:**你不能倾斜容器。

示例 1:

复制代码
输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

复制代码
输入:height = [1,1]
输出:1

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104
相关推荐
小雉系统9 小时前
BcoreOS安全通信架构:FsSession 抗算法后门安全设计
算法·安全·架构
投图匠10 小时前
十种不同风格的 CTP接口 框架
开发语言·python
2601_9679801112 小时前
深入理解词向量算法及其在Python中的实践
python·word2vec·glove·fasttext·词向量
129Lab12 小时前
电池循环测试数据自动化分析:用Python+AI工具构建一键式寿命评估流水线
python·数据分析·电池测试·数据自动化·寿命评估
treasure14012 小时前
【复古】浅尝Django前后端不分离
前端·css·python·django·bootstrap·html·web
Dmz丶13 小时前
前端转 AI 100 天 Day 44:前端集成实战——用 React 给 Agent 做个正式界面
python
唐墨12313 小时前
linux kernel 比较数据大小的宏定义
linux·算法
jay神13 小时前
基于 YOLOv8 的手势识别系统(Web 版)
前端·人工智能·python·深度学习·yolo·计算机视觉·计算机毕业设计
DeepVisionary13 小时前
阿里云上线旗舰多模态新模型,不公布跑分且限时14天退役
python·自动化