• 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.

  • 相关阅读:
    提交上了,却在iTunes Connect没有新版本的任何消息
    真机调试 —— An unknown error occurred.
    UI第二节——UIButton详解
    UI第一节—— UILable
    OC第九节——协议与代理
    补10月26日
    我看互联网第一约战
    接受自己的不完美---写在毕业之后的总结
    写给自己的学习之道
    越过山丘
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14670339.html
Copyright © 2020-2023  润新知