编程语言
首页 > 编程语言> > LeetCode刷题笔记 Java 腾讯 数组字符串 承最多水的容器

LeetCode刷题笔记 Java 腾讯 数组字符串 承最多水的容器

作者:互联网

题目:https://leetcode-cn.com/problems/container-with-most-water/

题目描述:

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器。

 题解:参考https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode-solution/

双指针

左右指针先放在最左最右

计算当前值,与最大比较

移动两者最小的再比较

public class Solution {
    public int maxArea(int[] height) {
        int l = 0, r = height.length - 1;
        int ans = 0;
        while (l < r) {
            // 求出当前值,与最大值比较
            int area = Math.min(height[l], height[r]) * (r - l);
            ans = Math.max(ans, area);
            // 移动最小的,再比较
            if (height[l] <= height[r]) {
                ++l;
            }
            else {
                --r;
            }
        }
        return ans;
    }
}

标签:容器,Java,cn,int,leetcode,height,ans,最多水,LeetCode
来源: https://blog.csdn.net/weixin_45322373/article/details/122413161