ethan

ethan

新知,热爱生活,码农,读书
twitter
email
github

LCR 11. 盛最多水的容器

給定一個長度為 n 的整數數組 height。有 n 條垂直線,第 i 條線的兩個端點是 (i, 0) 和 (i, height [i])。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。返回容器可以儲存的最大水量。
說明:你不能傾斜容器。
image.png
示例 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

解法 1: 雙指針法

func maxArea(height []int) int {
    left, right := 0,len(height)-1  // 定義左右指針,並確定走向為向中間移動
    water_level := 0
    for left < right { // 向中間移動的終止條件
        w := right -left;
        h := min(height[left], height[right])
        water_level = max(water_level, w*h)
        if height[left]<height[right] { // 左右指針移動條件
            left++
        }else {
            right--
        }
    }
    return water_level
}
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。