【Description】
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
【Idea】
看题立即推=>贪心思路。即只关注当前选择下的最优解,所以摒弃了全局最优的想法,而有限考虑局部最优解。
考虑在某index位置时,求解他的局部最优,即分解为:①当前可走的最大步数+②前往下一坐标后可走的最优步数,两者之和即为当前坐标下的最优解:
①的步数范围已知,记作curStep = [1, nums[index]
②的步数范围同样已知,记作nextStep = [1, nums[index+curStep]]
所以二者之和( curStep + nextStep)需要在对①的遍历基础上求得~
【Solution】
class Solution:
def jump(self, nums: List[int]) -> int:
length = len(nums)
if length <= 1:
return 0
if length == 2:
return 1
idx = 0
step = 0
while idx < length-1:
x = nums[idx]
if x == 1:
idx += 1
step += 1
continue
elif x >= length - idx -1:
return step + 1
else:
curStep = 1
maxN = 0
nextIdx = 1
while idx+curStep <= min(idx+x, length-1):
# 在当前可前进范围内,找出当前和下一步之和的最大步数,并存储对应位移
if maxN <= curStep + nums[idx+curStep]:
maxN = curStep + nums[idx+curStep]
nextIdx = idx + curStep
curStep += 1
step += 1
idx = nextIdx
return step
image.png
网友评论