Leetcode 45. Jump Game II

Problem

Given an array of non-negative integers, 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.

Algorithm

Greedy is good. The sum of position and the max jump length is the selection criteria.

Code

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        num_len = len(nums)
        if num_len < 2:
            return 0
        if nums[0] >= num_len-1:
            return 1
        
        end = nums[0]
        ans = 1
        new_end = end
        for i in range(1, num_len-1):
            if i <= end:
                if new_end < i + nums[i]:
                    new_end = i + nums[i]
                if i == end:
                    end = new_end
                    ans += 1
        return ans
Leetcode 45. Jump Game IILeetcode 45. Jump Game II 小白菜又菜 发布了1248 篇原创文章 · 获赞 199 · 访问量 116万+ 他的留言板 关注
上一篇:第十六章:开发工具-pdb:交互式调试工具-改变执行流-前跳


下一篇:1344. Jump Game V