算法题:盛最多水的容器

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

代码如下:

复制代码
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
相关推荐
Logintern092 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980114 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
民乐团扒谱机5 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T5 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
databook6 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer6 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
wy_hhxx6 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者7 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK8 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash