0045跳跃游戏II Marathon

给你一个非负整数数组 nums ,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

假设你总是可以到达数组的最后一个位置。

示例 1:

输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
  从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
示例 2:

输入: nums = [2,3,0,1,4]
输出: 2

提示:

1 <= nums.length <= 104
0 <= nums[i] <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii

参考:

python

# 0045.跳跃游戏II

class Solution:
    def jump(self, nums:[int]) ->int:
        """
        贪心,总能覆盖
        :param nums:
        :return:
        """
        if len(nums) == 1: return 0
        curDistance = 0 # 当前覆盖最远距离的下标
        ans = 0 # 步数
        nextDistance = 0 # 下一步覆盖的最远距离
        for i in range(len(nums)):
            nextDistance = max(nums[i]+i, nextDistance) # 更新下一步的覆盖距离
            if i == curDistance: # 遇到当前覆盖的最远距离的下标
                if curDistance != len(nums)-1:
                    ans += 1
                    curDistance = nextDistance
                    if nextDistance >= len(nums)-1: break
        return ans

golang

待完善
原文地址:https://www.cnblogs.com/davis12/p/15605594.html