盛最多水的容器

45 阅读1分钟

题目地址: leetcode-cn.com/problems/co…

使用的方法:双指针法
开始 l 指向数组的首位 ,r 指向数组末位。
遍历过程中去移动 l和r指向的位置,直到 l == r 。

容纳的水量是由
两个指针指向的数字中较小值 * 指针之间的距离
决定的。

所以在移动指针的时候需要 移动 指向的值小的一端(虽然我们不知道移动之后下一个值是否会更小),遍历完所有值,遍历过程中尽可能的往让面积变大的方向走。

最后的结果就是最大值

public int maxArea(int[] height) {
        int result = 0;
        int t = height.length;
        int l = 0,r = t - 1;
        //双指针
        while(l < r) {
            result = Math.max(Math.min(height[l], height[r]) * (r - l), result);
            if(height[l] < height[r]){
                l ++;
            } else{
                r --;
            }

        }
        return result;
    }