【Golang】LeetCode 11. 盛最多水的容器

11. 盛最多水的容器

题目描述

思路

这道题的思路比较简单,我们使用双指针来进行解决。

初始时我们设置左右两个指针,令l, r := 0, len(height) - 1。

然后,我们开始对整个数组进行由两侧到中间的遍历,遍历的条件就是l < r。

在遍历之前我们设置ans := 0 用于记录最终的答案。

每一次遍历的过程中,我们计算一次当前容器所能盛水的最大容量,计算公式就是curr := min(height[l], height[r]) * (r - l)。

计算之后,我们对ans进行一次更新,即:ans = max(ans, curr)。

最后,比较关键的是l和r的移动策略。我们采用贪心的思路,每一次我们想要得到的答案实际上都是尽可能大的盛水容积,而较小的一侧的高度则是水容积计算的短板,因此我们比较当前height[l]和height[r]的大小关系,如果height[l] > height[r],则令r --,否则l ++。

基于以上思路,我们写代码来解决问题。

Golang 题解

go 复制代码
func maxArea(height []int) int {
    ans := 0
    l, r := 0, len(height) - 1
    for l < r {
        curr := min(height[l], height[r]) * (r - l)
        ans = max(ans, curr)
        if height[l] > height[r] {
            r --
        } else {
            l ++
        }
    }

    return ans
}

Python 题解

python 复制代码
class Solution:
    def maxArea(self, height: List[int]) -> int:
        ans, l, r = 0, 0, len(height) - 1
        while l < r:
            curr = min(height[l], height[r]) * (r - l)
            ans = max(ans, curr)

            if height[l] > height[r]:
                r -= 1
            else:
                l += 1
        return ans
相关推荐
longlongzihan8 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
苦瓜打怪兽9 小时前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode
All for pursuit.13 小时前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
Navigator_Z13 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
旖旎夜光16 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
longlongzihan16 小时前
回溯法详解:LeetCode 46. 全排列
算法·leetcode·回溯
圣保罗的大教堂17 小时前
leetcode 3532. 针对图的路径存在性查询 I 中等
leetcode
longlongzihan1 天前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince1 天前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂1 天前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode