Skip to content

Commit e5a917f

Browse files
committed
feat: jump-game
1 parent 66a5104 commit e5a917f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

greedy.jump-game-ii.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
45. 跳跃游戏 II
7+
https://leetcode-cn.com/problems/jump-game-ii/
8+
给定一个非负整数数组,你最初位于数组的第一个位置。
9+
数组中的每个元素代表你在该位置可以跳跃的最大长度。
10+
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
11+
"""
12+
def jump(self, nums: List[int]) -> int:
13+
res = 0
14+
# 定义结束最小路径的暂停点
15+
end = 0
16+
# 最远距离
17+
max_pos = 0
18+
19+
for i in range(len(nums) - 1):
20+
# 当前最远跳动范围
21+
max_pos = max(nums[i] + i, max_pos)
22+
# 如果当前移动到暂停点,则将移动到下一个暂停点
23+
if i == end:
24+
end = max_pos
25+
res += 1
26+
27+
return res
28+
29+
30+
so = Solution()
31+
print(so.jump([3,2,1,0,4]))

greedy.jump-game.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
55. 跳跃游戏
7+
https://leetcode-cn.com/problems/jump-game/
8+
给定一个非负整数数组,你最初位于数组的第一个位置。
9+
数组中的每个元素代表你在该位置可以跳跃的最大长度。
10+
判断你是否能够到达最后一个位置。
11+
"""
12+
def canJump(self, nums: List[int]) -> bool:
13+
# 定义能跳到最远的下标
14+
k = 0
15+
for i in range(len(nums)):
16+
# 最远的距离
17+
if i > k:
18+
return False
19+
20+
# 更新能跳最远的下标
21+
k = max(k, i + nums[i])
22+
23+
return True
24+
25+
26+
so = Solution()
27+
print(so.canJump([3,2,1,0,4]))

0 commit comments

Comments
 (0)