[LeetCode] Container With Most Water

题目链接:https://leetcode.com/problems/container-with-most-water/

一开始我采用了遍历对比了每个可能的面积,后来参考了题目里给出的解决思路:

面积由距离和高度决定,而两个指定点之间的面积大小由矮的那个点决定,所以,先算出距离最长的两个点之间的面积。假设高的点b在最右端,这时如果把点b往左移动,面积是只可能变小,因为距离变小,而面积由矮的点a乘距离算出,所以,这时应该把点a右移,然后算出面积进行对比,以此类推,时间复杂度为o(n)

func maxArea(height []int) int {
    ret := 0
	l := 0
	r := len(height) - 1
	for {
		if l == r {
			break
		}
		h := height[r]
		d := r - l
		if height[l] < height[r] {
			h = height[l]
			l++
		} else {
			r--
		}
		container := h * d
		if container > ret {
			ret = container
		}
	}
	return ret
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章