题目描述
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。
解题代码
// 双指针法
func maxArea(height []int) int {
// 左右下标
indexLeft := 0
indexRight := len(height) - 1
max := 0
for indexLeft < indexRight {
if height[indexLeft] < height[indexRight] {
// 如果右边的值大,左指针右移一格
if max < height[indexLeft] *(indexRight - indexLeft) {
max = height[indexLeft] *(indexRight - indexLeft)
}
indexLeft++
} else {
// 如果左边的值大,右指针左移一格
if max < height[indexRight] *(indexRight - indexLeft) {
max = height[indexRight] *(indexRight - indexLeft)
}
indexRight--
}
}
return max
}