11. 盛最多水的容器 leetcode-hot100

65 阅读1分钟

image.png

方法:双指针

class Solution {
    public int maxArea(int[] height) {
        int l = 0; //左指针
        int r = height.length - 1; //右指针
        int res = Integer.MIN_VALUE; //面积
        while (r > l) {
            int h = Math.min(height[l], height[r]); //高度取两个指针最短的
            int area = h * (r - l); //计算面积
            res = Math.max(res, area); //更新最大面积
            
            //左右指针分别寻找大于当前高度的板
            while (r > l && height[l] <= h) {
                l++;
            }
            while (r > l && height[r] <= h) {
                r--;
            }
        }
        return res;
    }
}