LeetCode-11-盛最多水的容器

/*
    11.给定 n 个非负整数 a1a2...an,每个数代表坐标中的一个点 (i, ai) 。画 n 条垂直线,使得垂直线 i 的两个端点分别为 (i, ai)  (i, 0)    找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
    注意:你不能倾斜容器,n 至少是2
 */
//解法一,顺着题意的思路,结果正确,但是时间复杂度为O(n^2),效率低,时间超时,无法提交至LeetCode
    public static int maxArea(int[] height) {
        int maxArea = 0;
        for (int i = 0; i < height.length - 1; i++)
            for (int j = i + 1; j < height.length; j++)
                maxArea = Math.max( maxArea, height[i] > height[j] ? height[j] * (j - i) : height[i] * (j - i) );
        return maxArea;
    }

    //解法二,时间复杂度为O(n),效率大大提高,画个图就很容易理解了,从两边向中间靠计算面积
    public static int maxArea2(int[] height) {
        int ln = 0, rn = height.length - 1, maxArea = 0;
        while (ln < rn) {
            maxArea = Math.max( maxArea, height[ln] > height[rn] ? height[rn] * (rn - ln) : height[ln] * (rn - ln) );
            if (height[ln] > height[rn]) rn--;
            else ln++;
        }
        return maxArea;
    }


猜你喜欢

转载自blog.csdn.net/NestLu/article/details/80775535