(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
}
相关推荐
Tiandaren3 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
胚芽鞘6813 小时前
关于java项目中maven的理解
java·数据库·maven
chao_7894 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
CJi0NG4 小时前
【自用】JavaSE--算法、正则表达式、异常
java
Nejosi_念旧4 小时前
解读 Go 中的 constraints包
后端·golang·go
Hellyc5 小时前
用户查询优惠券之缓存击穿
java·redis·缓存
今天又在摸鱼5 小时前
Maven
java·maven
老马啸西风5 小时前
maven 发布到中央仓库常用脚本-02
java·maven
代码的余温5 小时前
MyBatis集成Logback日志全攻略
java·tomcat·mybatis·logback