[LeetCode in Python] 45 (H) jump game ii 跳跃游戏 II
题目
https://leetcode-cn.com/problems/jump-game-ii/
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
解题思路
index 0 1 2 3 4
nums 2 3 1 1 4
step 0 1 1 2 2
cur_end 0 2 2 4 4
max_end 2 4 4 4 8
- 以上面的例子来说
- step表示到达该位置的最小步数,分别是[0,1,1,2,2]
- 那么上述可以分为3段,cur_end就是用来记录当前步数下的右边界下标
- 遍历时,当i越过cur_end时,则需要更新cur_end为当前最大边界max_end,同时step++
- max_end的更新,要放在cur_end更新的后面
- 虽然代码不多,但是实际上本题比我想象的要麻烦一些……
代码
class Solution:
def jump(self, nums: List[int]) -> int:
# - example
#
# index 0 1 2 3 4
# nums 2 3 1 1 4
# step 0 1 1 2 2
# cur_end 0 2 2 4 4
# max_end 2 4 4 4 8
step = 0
cur_end, max_end = 0, 0
for i, n in enumerate(nums):
# - update cur_end after last cur_end
if i == cur_end + 1:
cur_end = max_end
step += 1
# - update max_end
max_end = max(max_end, i+n)
return step
爱生活,爱拉风