• Leetcode 45. Jump Game II


    Description: 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.

    Link: 45. Jump Game II

    Examples:

    Example 1:
    Input: nums = [2,3,1,1,4]
    Output: 2
    Explanation: The minimum number of jumps to reach the last index is 2. 
    Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [2,3,0,1,4] Output: 2 Example 3: Input: nums = [3,2,1] Output: 1 Example 4: Input: nums = [10,9,8,7,6,5,4,3,2,1,1,0] Output: 2 Example 5: Input: nums = [1,2,1,1,1] Output: 3

    思路: 贪心算法。当位于i位置时,可以跳动的最长距离是nums[i],我们可以选择跳动[1, 2, 3, ..., nums[i]],那么究竟跳几下,取决于跳完step后,step + nums[i+step]可以最大,所以以此为条件,选择从i位置跳动step步,循环直到 >= n-1.

    class Solution(object):
        def jump(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            i, jump = 0, 0
            while i < n-1:
                if i + nums[i] >= n-1:
                    return jump + 1
                else:
                    j, tmp, step = 1, 0, 1
                    while j <= nums[i]:
                        if j+nums[i+j] > tmp:
                            tmp = j + nums[i+j]
                            step = j
                        j += 1
                    i += step
                    jump += 1
            return jump

    日期: 2021-04-17 They will be moving into Melbourne Connect the day after tomorrow, but I'm still stuck at home, it's so terrible.

  • 相关阅读:
    学习Java的Day02
    学习Java的Day01
    多线程的了解
    几个MQ的区别
    HTML5——存储(cookie、localStorage、sessionStorage)的区别
    dubbo mock配置
    Springboot分布式,excel导出,运用POI导出,前端用的jsp
    oracle 添加字段和添加注释
    可以重复的Map:IdentityHashMap
    数组转list问题
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14670339.html
Copyright © 2020-2023  润新知