盛最多水的容器

62 阅读1分钟

题目链接:leetcode.cn/problems/co…

题解

func maxArea(height []int) int {
	var pre, post = 0, len(height) - 1
	var res, left, right int

	for pre < post {
		res = max(res, (post-pre)*min(height[pre], height[post]))
		left = height[pre]
		right = height[post]

		if height[pre] < height[post] {
			for pre < len(height) && height[pre] <= left {
				pre++
			}
		} else {
			for post >= 0 && height[post] <= right {
				post--
			}
		}

	}

	return res
}

func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

要点

  • 木桶原理,短板越长装的水越多;容器越宽装的水越多。

  • 使用双指针,先从最宽的容器开始,即左指针指向最左边,右指针指向最右边。当左边的高度低于右边的高度时,应该移动左边指针来提高短板的长度;当右边的高度低于左边高度时,应该移动右边指针来提高短板的长度。

  • 每次移动指针时,应该找到下一个更高的短板,如果遇到比当前还低的短板时,应该继续移动;因为短板变低了,那盛的水只会少不会多。