当前位置 博文首页 > 好好学习天天向上:leetcode-Algorithms-数组-11|盛最多水的容器

    好好学习天天向上:leetcode-Algorithms-数组-11|盛最多水的容器

    作者:[db:作者] 时间:2021-07-15 21:56

    原题

    在这里插入图片描述

    思路

    双指针,从两头开始,计算最大面积,如果左端点大于右端点,则尝试右端点退一位,如果右大于左,则左退一位。

    代码

    public class Solution_11 {
        public static void main(String[] args) {
            int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
            System.out.println(maxArea(height));
        }
    
        public static int maxArea(int[] height) {
            int max = 0;
            int x = 0;
            int y = height.length-1 ;
            while (x < y) {
                int h = Math.min(height[x] , height[y]);
                int l = Math.abs(x - y);
                max = Math.max(h * l, max);
                if (height[x] >= height[y]) {
                    y--;
                } else {
                    x++;
                }
            }
            return max;
        }
    }
    
    
    cs