盛水最多的容器-lc11题

1.经典题,题目就不上了,上个图吧,注意数组至少有两个值

 

 2.暴力破解法

直接算时间复杂度O(n^2),提交能够直接AC,但是时间消耗极大,只打败了7%的提交者

class Solution {
    public int maxArea(int[] height) {
        int len = height.length;
        int max = 0;
        for(int i = 0; i < len; i++)
        for (int j = i + 1; j < len; j++)
        {
            int h = height[i] > height[j] ?  height[j] :  height[i];
            int w = (j - i) * h;
            max = max > w ? max : w;
        }
        return max;
    }
}

3.双指针法

双指针这个解法没看过讲解真的很难想到。基本思路是两个指针分别指向数组的第一个位置和最后一个位置,然后数组元素较小的位置向前移动一位。(最难理解的一步,也是双指针的核心) 

为什么较小的元素向前移动?因为移动较大的,当前面积一定会变小,首先底部长度会缩小1,高度不变或者变小。而移动较小的则会有可能变大。所以,我们必定能找到最大值。

直接打败了92%的Java

        int len = height.length;
        int a = 0;
        int b = len - 1;
        int max = (b - a) * Math.min(height[a],height[b]);
        while(a < b - 1)
        {
            if(height[a] > height[b])
            {
                b--;
                max = Math.max(max, (b - a) * (height[a] > height[b] ? height[b] : height[a]));
            }
            else
            {
                a++;
                max = Math.max(max, (b - a) * (height[a] > height[b] ? height[b] : height[a]));
            }
        }

        return max;

 

posted @ 2020-08-07 18:14  LeftBody  阅读(140)  评论(0编辑  收藏  举报