28.盛最多水的容器

109 阅读2分钟

一、题目描述

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

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

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/co… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

二、题解

1. 遍历循环暴力法

  • 时间复杂度:由于用到内外循环,因此复杂度为O(n^2)
  • 空间复杂度:只需要常数级别的存储空间,因此为O(1)
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    const length = height.length;
    let maxArea = 0;
    for(let i = 0;i < length;i ++) 
        for(let j = i + 1;j < length;j ++) {
            const area = (j - i) * Math.min(height[i],height[j]);
            maxArea = area > maxArea? area:maxArea;
        }
    return maxArea;
};

2.双指针法

  • 时间复杂度: O(n),一次扫描
  • 空间复杂度: O(1)
  • 思路:这种方法背后的思路在于,两线段之间形成的区域总是会受到其中较短那条长度的限制。此外,两线段距离越远,得到的面积就越大。

我们在由线段长度构成的数组中使用两个指针,一个放在开始,一个置于末尾。 此外,我们会使用变量 maxarea 来持续存储到目前为止所获得的最大面积。 在每一步中,我们会找出指针所指向的两条线段形成的区域,更新 maxareamaxarea,并将指向较短线段的指针向较长线段那端移动一步。

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    const length = height.length;
    let maxArea = 0;
    let i = 0, j = height.length - 1;
    while(i < j) {
        const area = (j - i) * Math.min(height[i],height[j]);
        maxArea = area > maxArea ? area : maxArea;
        if(height[i] <= height[j]) {
            i ++;
        } else  {
            j --;
        }
    }
    return maxArea;
};