实现说明
双指针求盛最多水的容器可以归结为函数 maxArea、main。
驱动整个流程的是 for left < right 这一个循环。
使用要点
main按顺序串起maxArea;运行文件就会把这个流程跑一遍。
常见问题
「双指针求盛最多水的容器」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
主签名形如 func maxArea(height []int) int
核心语句
func main() {
fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
fmt.Println(maxArea([]int{1, 1}))
fmt.Println(maxArea([]int{4, 3, 2, 1, 4}))
}
代码示例
package main
import "fmt"
// maxArea: container with most water — move the shorter wall inward,
// because it is the one capping the area
func maxArea(height []int) int {
left, right := 0, len(height)-1
best := 0
for left < right {
width := right - left
h := height[left]
if height[right] < h {
h = height[right]
}
if area := width * h; area > best {
best = area
}
if height[left] < height[right] {
left++
} else {
right--
}
}
return best
}
func main() {
fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
fmt.Println(maxArea([]int{1, 1}))
fmt.Println(maxArea([]int{4, 3, 2, 1, 4}))
}