LeetCode45. 跳跃游戏 II

45. 跳跃游戏 II

给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:
输入: [2,3,1,1,4]
输出: 2

解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

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

class Solution:
    def jump(self,nums):
        index = 0
        n = 0
        i = 0
        if len(nums) == 1 or not nums:
            return 0
        while True:
            ax = nums[i]
            if nums[i] + i >= len(nums) -1:
                return n+1
            for j,k in enumerate(range(i,nums[i]+i+1)):
                if nums[k]+j >ax:
                    ax = nums[k]+j
                    index = j

            if index == 0:
                index = nums[i]

            i += index
            n += 1

            if i>= len(nums)-1:
                return n
            index = 0
发布了110 篇原创文章 · 获赞 3 · 访问量 4068

猜你喜欢

转载自blog.csdn.net/qq_33357094/article/details/105220279
今日推荐