Skip to content

Commit 588357a

Browse files
committed
fix leetcode 0011 with go
1 parent a819621 commit 588357a

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# 11. 盛最多水的容器
2+
3+
## 链接
4+
https://leetcode-cn.com/problems/container-with-most-water/
5+
6+
## 难度
7+
中等
8+
9+
## 描述
10+
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
11+
12+
说明:你不能倾斜容器,且 n 的值至少为 2。
13+
14+
![](https://aliyun-lc-upload.oss-cn-hangzhou.aliyuncs.com/aliyun-lc-upload/uploads/2018/07/25/question_11.jpg)
15+
16+
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
17+
18+
示例
19+
```text
20+
输入: [1,8,6,2,5,4,8,3,7]
21+
输出: 49
22+
```
23+
24+
## 思路
25+
从数组两边往里推进,找出最大的面积
26+
为了使面积最大化,长度短的往里进一,长度长的不变
27+
28+
## 疑惑
29+
30+
两段代码
31+
```go
32+
// 代码 A
33+
func max(a int, b int) (r int) {
34+
r = a
35+
if a < b {
36+
r = b
37+
}
38+
return
39+
}
40+
```
41+
42+
```go
43+
// 代码 B
44+
func max(a int, b int) int {
45+
if a >= b {
46+
return a
47+
}
48+
return b
49+
}
50+
```
51+
52+
在这个程序里,不同的 max 实现,代码 A 就是比代码 B 快 10ms + ,虽然 10ms 很小,但是对于只需要执行 20-30 ms 的程序而言,差异就是 50%
53+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package _011_Container_With_Most_Water
2+
3+
func maxArea(height []int) int {
4+
area, left, right := 0, 0, len(height)-1
5+
for left < right {
6+
if height[left] < height[right] {
7+
area = max(area, height[left]*(right-left))
8+
left++
9+
} else {
10+
area = max(area, height[right]*(right-left))
11+
right--
12+
}
13+
}
14+
return area
15+
}
16+
17+
func max(a int, b int) (r int) {
18+
r = a
19+
if a < b {
20+
r = b
21+
}
22+
return
23+
}

0 commit comments

Comments
 (0)