力扣Leetcode 11. 盛最多水的容器

盛最多水的容器

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

img

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例:

输入:[1,8,6,2,5,4,8,3,7]
输出:49

题解

暴力法(超时)

显然直接暴力会超时 思路看代码就能理解到

int maxArea(vector<int>& height) {
        int max = 0;
        int L = height.size();
        for (int i = 0; i < L-1; i++){
            for (int j = 1; j < L; j++){
                int temp = min(height[i], height[j]) * (j-i);
                if(temp > max) max = temp;
        }
    }
    return max;
}

双指针法

头尾设定指针 根据短板效应 最大体积必然是又两侧最短的板决定 所以让较短的板往中间移动 直至指针相遇

int maxArea(vector<int> &height)
    {
        int result = 0;
        int heightSize = int(height.size());
        int leftIndex = 0;
        int rightIndex = heightSize - 1;

        while (leftIndex != rightIndex)
        {
            int tmpHeight;
            int tmpWidth = rightIndex - leftIndex;
            //短的一侧向中间移动
            if (height[leftIndex] < height[rightIndex])
            {
                tmpHeight = height[leftIndex];
                leftIndex++;
            }
            else
            {
                tmpHeight = height[rightIndex];
                rightIndex--;
            }
            int tmpResult = tmpWidth * tmpHeight;
            if (tmpResult > result)
            {
                result = tmpResult;
            }
        }
        return result;
}

猜你喜欢

转载自www.cnblogs.com/coderzjz/p/12727652.html