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

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



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

先从最边上的两侧开始遍历:l=0,r=n-1
下一个最优解肯定是让高度小的那一侧移动产生的:if(heightl<heightr) 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
}
相关推荐
dialect_8 小时前
KMP算法
开发语言·c++·算法
captain3768 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
reikocao8 小时前
卡尔曼滤波的动态机制:P如何改变融合权重
算法
Novproxy_Z8 小时前
商用代理避坑:如何识别商家拿机房 IP 冒充住宅 IP
java·网络·tcp/ip
漂流瓶jz9 小时前
UVA-1612 猜名次 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·排序·aoapc·算法竞赛入门经典
夕除9 小时前
Redis 过期策略
redis·笔记·面试
吞下星星的少年·-·9 小时前
Div.2 CF 1130B题(构造,贪心)
算法·贪心·构造
文丑颜不良啊9 小时前
LeetCode1481~1500题目解析
java·leetcode
2601_962885729 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
前端精髓9 小时前
调用openrouter的免费API模型
java·前端·javascript