letcode---11.盛最多水的容器

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介: 简单算法

题目

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

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

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

说明:你不能倾斜容器。
image.png

方案一

直接暴力解决
class Solution:

def maxArea(self, height: List[int]) -> int:
    list1 = []
    for i in range(0, len(height)):
        for j in range(i+1, len(height)):
            h = min(height[i], height[j])
            s =  h * (j-i)
            list1.append(s)
    a = max(list1)
    return a

方案二

采用双指针,我们要将短板每次向内移动一格,面积才能增大。先将左右两端双指针化,将短板内移,直到两指针相遇移出,
class Solution:

def maxArea(self, height: List[int]) -> int:
    i, j, res = 0, len(height) - 1, 0
    while i < j:
        if height[i] < height[j]:
            res = max(res, height[i] * (j - i))
            i += 1
        else:
            res = max(res, height[j] * (j - i))
            j -= 1
    return res
相关文章
|
3天前
|
存储 容器
LeetCode刷题---11. 盛最多水的容器(双指针-对撞指针)
LeetCode刷题---11. 盛最多水的容器(双指针-对撞指针)
|
7月前
|
算法 容器
【算法专题突破】双指针 - 盛最多水的容器(4)
【算法专题突破】双指针 - 盛最多水的容器(4)
20 0
|
7月前
|
算法 测试技术 容器
【算法挨揍日记】day02——双指针算法_快乐数、盛最多水的容器
题目: 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」 定义为:
39 0
|
3天前
|
容器
leetcode代码记录(盛最多水的容器
leetcode代码记录(盛最多水的容器
9 1
|
3天前
|
容器
11.盛最多水的容器
11.盛最多水的容器
13 0
|
3天前
|
容器
【力扣】11. 盛最多水的容器
【力扣】11. 盛最多水的容器
|
3天前
|
容器
LeetCode题:11. 盛最多水的容器
LeetCode题:11. 盛最多水的容器
16 0
|
3天前
|
Python 容器 人工智能
Python每日一练(20230402) 对称二叉树、全排列、盛最多水的容器
Python每日一练(20230402) 对称二叉树、全排列、盛最多水的容器
29 0
Python每日一练(20230402) 对称二叉树、全排列、盛最多水的容器
|
3天前
|
人工智能 容器
leetcode-11:盛最多水的容器
leetcode-11:盛最多水的容器
29 0
|
3天前
|
存储 算法 Java
Leetcode算法系列| 11. 盛最多水的容器
Leetcode算法系列| 11. 盛最多水的容器