LeetCode 55
https://leetcode.cn/problems/jump-game/
思路分析
关键是判断能否到达终点,不用管每一步跳跃到哪里,而是尽可能的跳跃到最远的位置
看最多能覆盖到哪里,只要不断更新能覆盖的距离,最后能覆盖到末尾就行了
具体执行:
代码实现
class Solution:
def canJump(self, nums: List[int]) -> bool:
cover = 0
n = len(nums)
for i in range(n):
# 判断是能能够到达 i 的位置
if cover < i:
return False
cover = max(i + nums[i], cover)
if cover >= n - 1:
return True
return False
LeetCode 45
https://leetcode.cn/problems/jump-game-ii/
思路分析
贪心+双指针
设置四个变量
代码实现
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
steps = 0
max_position = 0
right = 0
for left in range(n-1):
max_position = max(max_position, nums[left] + left)
if left == right:
right = max_position
steps += 1
return steps