Skip to content

Commit 5b67824

Browse files
committed
update the 45 problem
1 parent 628c27d commit 5b67824

File tree

2 files changed

+58
-3
lines changed

2 files changed

+58
-3
lines changed

src/0045.Jump-Game-II/Solution.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package Solution
22

33
import (
4+
"fmt"
45
"math"
56
)
67

@@ -54,6 +55,34 @@ func jump2(nums []int) int {
5455
return res
5556
}
5657

58+
/**
59+
1
60+
61+
*/
62+
func jump3(nums []int) int {
63+
// 如果数组小于2,则说明不用跳跃返回0
64+
if len(nums) < 2 {
65+
return 0
66+
}
67+
// 当前可达到的最远位置,遍历过程中可达到最远位置,最小步数
68+
current_max_index, pre_max_max_index, jump_min := nums[0], nums[0], 1
69+
70+
for i := 1; i < len(nums); i++ {
71+
// 如果无法向前移动才进行跳跃
72+
if i > current_max_index {
73+
jump_min++
74+
// 更新当前可以到达的最远位置
75+
current_max_index = pre_max_max_index
76+
}
77+
if pre_max_max_index < nums[i]+i {
78+
// 跟新最远位置
79+
pre_max_max_index = nums[i] + i
80+
}
81+
fmt.Println("i:", i, current_max_index, pre_max_max_index, jump_min)
82+
}
83+
return jump_min
84+
}
85+
5786
func Min(x, y int) int {
5887
if x > y {
5988
return y

src/0045.Jump-Game-II/Solution_test.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,10 @@ func TestSolution2(t *testing.T) {
3636
inputs []int
3737
expect int
3838
}{
39-
{"TestCacse 1", []int{2, 3, 1, 1, 4}, 2},
40-
{"TestCacse 1", []int{2}, 0},
41-
{"TestCacse 1", []int{10, 3, 4}, 1},
39+
{"TestCase 1", []int{2, 3, 1, 1, 4}, 2},
40+
{"TestCase 1", []int{2}, 0},
41+
{"TestCase 1", []int{10, 3, 4}, 1},
42+
{"TestCase 4", []int{4, 1, 1, 3, 1, 1, 1}, 2},
4243
}
4344

4445
// 开始测试
@@ -53,6 +54,31 @@ func TestSolution2(t *testing.T) {
5354
}
5455
}
5556

57+
func TestSolution3(t *testing.T) {
58+
// 测试用例
59+
cases := []struct {
60+
name string
61+
inputs []int
62+
expect int
63+
}{
64+
{"TestCase 1", []int{2, 3, 1, 1, 4}, 2},
65+
{"TestCase 2", []int{2}, 0},
66+
{"TestCase 3", []int{10, 3, 4}, 1},
67+
{"TestCase 4", []int{4, 1, 1, 3, 1, 1, 1}, 2},
68+
}
69+
70+
// 开始测试
71+
for _, c := range cases {
72+
t.Run(c.name, func(t *testing.T) {
73+
ret := jump3(c.inputs)
74+
if !reflect.DeepEqual(ret, c.expect) {
75+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
76+
c.expect, ret, c.inputs)
77+
}
78+
})
79+
}
80+
}
81+
5682
// 压力测试
5783
func BenchmarkSolution(b *testing.B) {
5884

0 commit comments

Comments
 (0)