题目:盛最多水的容器 点击跳转


题目描述

在这里插入图片描述

暴力超时

class Solution {
    public int maxArea(int[] height) {
        int res = 0;
        for(int slow = 0;slow<height.length;slow++){
            for(int fast = slow+1;fast<height.length;fast++){
                int x = fast-slow;
                int y = Math.min(height[slow],height[fast]);
                int xy = x*y;
                res = Math.max(res, xy);                             
            }
        }
        return res;
    }
}

左右双指针(对撞指针)

谁短移动谁

class Solution {
    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length-1;
        int res = 0;
        while(left<right){
            int x = right-left;
            int y = Math.min(height[left],height[right]);
            int xy = x*y;
            res = Math.max(res, xy);
            // 移动较短的那一边
            if(height[left]<height[right]){
                left++;
            }else{
                right--;
            }
        }
        return res;
    }
}

更多推荐