8000 add 42 solution · reverse/awesome-golang-leetcode@06a4fb8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 06a4fb8

Browse files
committed
add 42 solution
1 parent 8e3c739 commit 06a4fb8

File tree

2 files changed

+49
-11
lines changed

2 files changed

+49
-11
lines changed
Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,44 @@
11
package Solution
22

3-
func Solution(x bool) bool {
3+
import "fmt"
4+
5+
// 三次线性扫描
6+
func trap(height []int) int {
7+
if len(height) == 0 {
8+
return 0
9+
}
10+
11+
n, ans := len(height), 0
12+
leftMax, rightMax := make([]int, n), make([]int, n)
13+
14+
// 求第i个矩形左边最高矩形的高度
15+
leftMax[0] = height[0]
16+
for i := 1; i < n; i++ {
17+
leftMax[i] = max(leftMax[i-1], height[i])
18+
}
19+
// 求第i个矩形右边最高矩形的高度
20+
rightMax[n-1] = height[n-1]
21+
for i := n - 2; i >= 0; i-- {
22+
rightMax[i] = max(rightMax[i+1], height[i])
23+
}
24+
25+
for i := 0; i < n; i++ {
26+
fmt.Println(i, leftMax[i], rightMax[i], height[i])
27+
ans += min(leftMax[i], rightMax[i]) - height[i]
28+
}
29+
30+
return ans
31+
}
32+
33+
func max(x, y int) int {
34+
if x > y {
35+
return x
36+
}
37+
return y
38+
}
39+
func min(x, y int) int {
40+
if x > y {
41+
return y
42+
}
443
return x
544
}

src/0042.Trapping-Rain-Water/Solution_test.go

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,27 @@ package Solution
22

33
import (
44
"reflect"
5+
"strconv"
56
"testing"
67
)
78

89
func TestSolution(t *testing.T) {
910
// 测试用例
1011
cases := []struct {
1112
name string
12-
inputs bool
13-
expect bool
13+
inputs []int
14+
expect int
1415
}{
15-
{"TestCacse 1", true, true},
16-
{"TestCacse 1", true, true},
17-
{"TestCacse 1", false, false},
16+
{"TestCase", []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}, 6},
1817
}
1918

2019
// 开始测试
21-
for _, c := range cases {
22-
t.Run(c.name, func(t *testing.T) {
23-
ret := Solution(c.inputs)
24-
if !reflect.DeepEqual(ret, c.expect) {
20+
for i, c := range cases {
21+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
22+
got := trap(c.inputs)
23+
if !reflect.DeepEqual(got, c.expect) {
2524
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
26-
c.expect, ret, c.inputs)
25+
c.expect, got, c.inputs)
2726
}
2827
})
2928
}

0 commit comments

Comments
 (0)
0