题目描述
Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
解题思路
看到题目第一感觉是用递归!但是一看输入的 scale,感觉递归有可能超时。百度一下,看到 “贪心” 二字,有了点思路,但是我再一看别人的代码,感觉不是很好理解。于是自己写吧,现将规律奉上:对于每一次选择,选取最有潜力的那一个位置。潜力的含义在于这个位置能带来的下一步的收益,从本题来看,收益在于可以走到的距离。理解了这个,请看下面的代码。
代码
class Solution:
def jump(self, nums: List[int]) -> int:
if len(nums) < 2:
return 0
cur = 0
ans = 0
while 1 # 坚信一定有 break:
cur_max_reach = cur + nums[cur] #当前位置可以辐射的范围
if cur_max_reach >= len(nums) - 1: # 如果可以辐射到最后一个则退出
ans += 1 # 切记这一步添加
break
next_max_reach = cur + nums[cur] # 辐射范围内的最大潜力
next_pos = cur_max_reach # 最大潜力位置就是下一步 cur 的值
for i in range(cur + 1, cur + nums[cur] + 1):
if i + nums[i] > next_max_reach:
next_max_reach = i + nums[i]
next_pos = i
cur = next_pos
ans += 1 # 走一步
return ans