Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

11. 盛最多水的容器 #145

Open
S-T-D opened this issue Sep 7, 2021 · 0 comments
Open

11. 盛最多水的容器 #145

S-T-D opened this issue Sep 7, 2021 · 0 comments

Comments

@S-T-D
Copy link
Owner

S-T-D commented Sep 7, 2021

原题地址

11. 盛最多水的容器

 

题目描述

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

说明:你不能倾斜容器。

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

示例 2
输入:height = [1,1]
输出:1

示例 3
输入:height = [4,3,2,1,4]
输出:16

示例 4
输入:height = [1,2,1]
输出:2
 
提示:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104

 

题解 —— 双指针

思路

参考

代码

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let i = 0;
    let j = height.length - 1;
    let res = 0;
    while (i < j) {
        // 谁小就移动谁,移动短板,因为面积由短板决定
        // 移动长板,可能使短板不变或更短,面积也就更小
        if (height[i] < height[j]) {
            res = Math.max(res, (j - i) * height[i]);
            i++;
        } else {
            res = Math.max(res, (j - i) * height[j]);
            j--;
        }
    }
    return res;
};

复杂度

  • 时间:O(n)
  • 空间:O(1)

 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant