Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 0103fae

Browse files
aQuaaQua
aQua
authored and
aQua
committed
added Problem 11
1 parent 4a1e159 commit 0103fae

File tree

2 files changed

+24
-26
lines changed

2 files changed

+24
-26
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
22

33
## 题目
4+
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
45

6+
就是说,x轴上在1,2,...,n点上有许多垂直的线段,长度依次是a1, a2, ..., an。找出两条线段,使他们和x抽围成的面积最大。面积公式是 Min(ai, aj) X |j - i|
57

68
## 解题思路
9+
穷举法是O(n^2)的复杂度,会触发leetcode的时间限制。
710

8-
9-
## 总结
10-
11-
11+
O(n)的复杂度的解法是,保持两个指针i,j;分别指向长度数组的首尾。如果ai 小于aj,则移动i向后(i++)。反之,移动j向前(j--)。如果当前的area大于了所记录的area,替换之。这个想法的基础是,如果i的长度小于j,无论如何移动j,短板在i,不可能找到比当前记录的area更大的值了,只能通过移动i来找到新的可能的更大面积。
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,33 @@
11
package Problem0011
22

33
func maxArea(height []int) int {
4+
// 从两端开始寻找,至少保证了宽度是最大值
5+
i, j := 0, len(height)-1
46
max := 0
5-
for i := 0; i < len(height); i++ {
6-
for j := 0; j < len(height); j++ {
7-
temp := h(height, i, j) * w(i, j)
8-
if temp > max {
9-
max = temp
10-
}
11-
}
12-
}
137

14-
return max
15-
}
8+
for i < j {
9+
a, b := height[i], height[j]
10+
h := min(a, b)
1611

17-
// h 高度
18-
func h(h []int, i, j int) int {
19-
a, b := h[i], h[j]
12+
area := h * (j - i)
13+
if max < area {
14+
max = area
15+
}
2016

21-
if a < b {
22-
return a
17+
// 朝着area具有变大的可能性方向变化。
18+
if a < b {
19+
i++
20+
} else {
21+
j--
22+
}
2323
}
2424

25-
return b
25+
return max
2626
}
2727

28-
// w 宽度
29-
func w(a, b int) int {
30-
if a < b {
31-
return b - a
28+
func min(i, j int) int {
29+
if i <= j {
30+
return i
3231
}
33-
34-
return a - b
32+
return j
3533
}

0 commit comments

Comments
 (0)