(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)

题目:11. 盛最多水的容器



思路:双指针+贪心。时间复杂度0(n)。

先从最边上的两侧开始遍历:l=0,r=n-1
下一个最优解肯定是让高度小的那一侧移动产生的:if(height[l]<height[r]) l++; else r--;

C++版本:

cpp 复制代码
class Solution {
public:
    int maxArea(vector<int>& height) {
        int n=height.size();
        int l=0,r=n-1;
        int mx=0;
        while(l<r){
            mx=max(mx,min(height[l],height[r])*(r-l));
            if(height[l]<height[r]) l++;
            else r--;
        }
        return mx;
    }
};

JAVA版本:

java 复制代码
class Solution {
    public int maxArea(int[] height) {
        int n=height.length;
        int l=0,r=n-1;
        int mx=0;
        while(l<r){
            mx=Math.max(mx,Math.min(height[l],height[r])*(r-l));
            if(height[l]<height[r]) l++;
            else r--;
        }
        return mx;
    }
}

GO版本:

go 复制代码
func maxArea(height []int) int {
    n:=len(height)
    l,r:=0,n-1
    mx:=0
    for l<r {
        mx=max(mx,min(height[l],height[r])*(r-l))
        if height[l]<height[r] {
            l++
        }else {
            r--
        }
    }
    return mx
}
相关推荐
期待のcode1 小时前
MyBatisX插件
java·数据库·后端·mybatis·springboot
yaoh.wang3 小时前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
T1ssy4 小时前
布隆过滤器:用概率换空间的奇妙数据结构
算法·哈希算法
醇氧4 小时前
【Windows】优雅启动:解析一个 Java 服务的后台启动脚本
java·开发语言·windows
sunxunyong4 小时前
doris运维命令
java·运维·数据库
菜鸟起航ing4 小时前
Spring AI 全方位指南:从基础入门到高级实战
java·人工智能·spring
未来魔导4 小时前
go语言中json操作总结
数据分析·go·json
古城小栈4 小时前
Docker 多阶段构建:Go_Java 镜像瘦身运动
java·docker·golang
hetao17338374 小时前
2025-12-12~14 hetao1733837的刷题笔记
数据结构·c++·笔记·算法
椰子今天很可爱4 小时前
五种I/O模型与多路转接
linux·c语言·c++