【LeetCode】11. 盛最多水的容器(Container With Most Water)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27124771/article/details/84584655

英文练习 | 中文练习

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


示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

解题思路: 两线段之间形成的区域总是会受到其中较短那条长度的限制,同时,两线段距离越远,得到的面积就越大。使用两个指针,一个放在开始,一个放在末尾,更新存储的最大面积,将指向较短线段的指针向较长线段那端移动一步。

public int maxArea(int[] height) {
    int start = 0,end = height.length - 1;
    int maxArea = 0;
    while(end > start){
        maxArea = Math.max(maxArea, Math.min(height[start], height[end]) * (end - start));
        if(height[start] > height[end]) end--;
        else start++;
    }
    return maxArea;
}

猜你喜欢

转载自blog.csdn.net/qq_27124771/article/details/84584655