算法题:盛最多水的容器

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

代码如下:

复制代码
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
相关推荐
醒过来摸鱼20 小时前
Java classloader
java·开发语言·python
superman超哥21 小时前
仓颉语言中元组的使用:深度剖析与工程实践
c语言·开发语言·c++·python·仓颉
小鸡吃米…21 小时前
Python - 继承
开发语言·python
祁思妙想21 小时前
Python中的FastAPI框架的设计特点和性能优势
开发语言·python·fastapi
LYFlied21 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠21 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
Dingdangcat8621 小时前
反恐精英角色识别与定位-基于改进的boxinst_r101_fpn_ms-90k_coco模型实现
python
世界唯一最大变量1 天前
利用自定义积分公式,目前可以求出所有1元方程和1元积分的近似值
python
写代码的【黑咖啡】1 天前
深入理解 Python 中的模块(Module)
开发语言·python
ytttr8731 天前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab