Skip to content

Commit fbaff68

Browse files
Merge pull request youngyangyang04#2399 from Cupcc/master
添加go语言贪心优化版本在0045.跳跃游戏II.md
2 parents 4e0ec1f + 39f25c4 commit fbaff68

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

problems/0045.跳跃游戏II.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,34 @@ class Solution:
285285

286286
### Go
287287

288+
289+
```go
290+
/**
291+
* @date: 2024 Jan 06
292+
* @time: 13:44
293+
* @author: Chris
294+
**/
295+
// 贪心算法优化版
296+
297+
// 记录步骤规则:每超过上一次可达最大范围,需要跳跃一次,次数+1
298+
// 记录位置:i == lastDistance + 1
299+
func jump(nums []int) int {
300+
// 根据题目规则,初始位置为nums[0]
301+
lastDistance := 0 // 上一次覆盖范围
302+
curDistance := 0 // 当前覆盖范围(可达最大范围)
303+
minStep := 0 // 记录最少跳跃次数
304+
305+
for i := 0; i < len(nums); i++ {
306+
if i == lastDistance+1 { // 在上一次可达范围+1的位置,记录步骤
307+
minStep++ // 跳跃次数+1
308+
lastDistance = curDistance // 记录时才可以更新
309+
}
310+
curDistance = max(nums[i]+i, curDistance) // 更新当前可达的最大范围
311+
}
312+
return minStep
313+
}
314+
```
315+
288316
```go
289317
// 贪心版本一
290318
func jump(nums []int) int {

0 commit comments

Comments
 (0)