Skip to content

Commit fe125f1

Browse files
committed
贪心: 跳跃游戏
Change-Id: I617aa366136d2a6009110dd856a287f050544f15
1 parent c777cfb commit fe125f1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

go/leetcode/55.跳跃游戏.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* @lc app=leetcode.cn id=55 lang=golang
3+
*
4+
* [55] 跳跃游戏
5+
*
6+
* https://leetcode-cn.com/problems/jump-game/description/
7+
*
8+
* algorithms
9+
* Medium (36.07%)
10+
* Likes: 326
11+
* Dislikes: 0
12+
* Total Accepted: 34K
13+
* Total Submissions: 93.7K
14+
* Testcase Example: '[2,3,1,1,4]'
15+
*
16+
* 给定一个非负整数数组,你最初位于数组的第一个位置。
17+
*
18+
* 数组中的每个元素代表你在该位置可以跳跃的最大长度。
19+
*
20+
* 判断你是否能够到达最后一个位置。
21+
*
22+
* 示例 1:
23+
*
24+
* 输入: [2,3,1,1,4]
25+
* 输出: true
26+
* 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
27+
*
28+
*
29+
* 示例 2:
30+
*
31+
* 输入: [3,2,1,0,4]
32+
* 输出: false
33+
* 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
34+
*
35+
*
36+
*/
37+
38+
// 与45求最小步数类似,这里不需要关注left
39+
// 只需要关注当前i>=right,当i==right时,那就是说靠跳跃已经跳不过去i这个位置了
40+
func canJump(nums []int) bool {
41+
right := 0
42+
for i := 0; i < len(nums); i++ {
43+
if nums[i] + i > right {
44+
right = nums[i] + i
45+
}
46+
if right >= len(nums) - 1 {
47+
return true
48+
}
49+
if i >= right {
50+
return false
51+
}
52+
}
53+
return false
54+
}
55+

0 commit comments

Comments
 (0)