11.盛最多水的容器

2024/3/9

# Heading

    11.盛最多水的容器 (opens new window)

    Tags: algorithms bloomberg array two-pointers

    Langs: c cpp csharp dart elixir erlang golang java javascript kotlin php python python3 racket ruby rust scala swift typescript

    • algorithms
    • Medium (60.06%)
    • Likes: 4876
    • Dislikes: -
    • Total Accepted: 1.2M
    • Total Submissions: 2M
    • Testcase Example: '[1,8,6,2,5,4,8,3,7]'

    给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

    找出其中的两条线,使得它们与 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
    

     

    提示:

    • n == height.length
    • 2 <= n <= 105
    • 0 <= height[i] <= 104
    /*
     * @lc app=leetcode.cn id=11 lang=javascript
     *
     * [11] 盛最多水的容器
     * 双指针法
     */
    
    // @lc code=start
    /**
     * @param {number[]} height
     * @return {number}
     */
    var maxArea = function(height) {
        if (height.length < 2) {
            return 0
        }
    
        let i = 0
        let j = height.length - 1
        let maxArea = 0
        while (i < j) {
            const tempAera = (j - i) * Math.min(height[i], height[j])
            if (tempAera > maxArea) {
                maxArea = tempAera
            }
            if (height[i] > height[j]) {
                const tempHeight = height[j--]
                while (height[j] <= tempHeight) {
                    j--
                }
            } else {
                const tempHeight = height[i++]
                while (height[i] <= tempHeight) {
                    i++
                }
            }
        }
    
        return maxArea
    }
    // @lc code=end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41