一、题目描述
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
二、题目分析
原则:本题符合木桶理论,最短的木板决定桶容量。
思路1:暴力破解法,循环计算所有可能的容量组合,存储在数组中,最后筛选出最大的,复杂度太高,肯定不是好的解决方法,放弃;
思路2:双指针法,采用首尾指针,通过比较首尾数字的大小(木板长短),不停的根据策略(比较指针指向数据的大小,左小则左指针右移,右小则右指针左移)向中间逼近,直到指针相遇,此过程已经覆盖了可能的最大值,通过临时变量保存最大值即可。
三、代码实现
// leetcode_11. 盛最多水的容器
// 非最优代码方案,欢迎继续优化
package main
import "fmt"
func maxArea(height []int) int {
max := 0
i := 0
j := len(height) - 1
for {
if j <= i {
break
}
tmpMax := 1
if height[i] <= height[j] {
tmpMax = height[i]
i++
} else if height[i] > height[j] {
tmpMax = height[j]
j--
}
tmpMax = tmpMax * (j - i + 1)
if max < tmpMax {
max = tmpMax
}
}
return max
}
func main() {
height := []int{1, 2}
fmt.Println("arr: ", height, " maxArea: ", maxArea(height))
height = []int{1, 1}
fmt.Println("arr: ", height, " maxArea: ", maxArea(height))
height = []int{3, 1, 2, 3}
fmt.Println("arr: ", height, " maxArea: ", maxArea(height))
height = []int{1, 8, 6, 2, 5, 4, 8, 3, 7}
fmt.Println("arr: ", height, " maxArea: ", maxArea(height))
}
打印结果
arr: [1 2] maxArea: 1
arr: [1 1] maxArea: 1
arr: [3 1 2 3] maxArea: 9
arr: [1 8 6 2 5 4 8 3 7] maxArea: 49
Process finished with exit code 0
——2019-07-12——