【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)

最后,比较关键的是lr的移动策略。我们采用贪心的思路,每一次我们想要得到的答案实际上都是尽可能大的盛水容积,而较小的一侧的高度则是水容积计算的短板,因此我们比较当前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
相关推荐
琢磨先生David7 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝7 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll7 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐7 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶7 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER7 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了7 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333337 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录7 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1237 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode