zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    go http client, http server
    如何使用Django 启动命令行及执行脚本
    golang cannot assign to
    非root用户执行程序---sudo的使用
    kafka 安装与配置
    golang kafka client
    Python处理Excel文档之openpyxl
    Windows下安装使用Pypcap
    xlutils模块
    Python xlrd、xlwt、xlutils修改Excel文件
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14670339.html
Copyright © 2011-2022 走看看