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.

  • 相关阅读:
    线程池
    自定义死锁
    不安全线程取钱
    JUC Lock实现类ReentrantLock使用说明
    同步方法跟同步方法块 synchronized
    线程的管程法跟信号灯法_生产者消费模式
    CopyOnWriteArrayList JUC当中安全容器
    inserttextatcursorinacontenteditablediv
    Android开发——NDK开发入门
    Linux下线程同步对象(1)——互斥量
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14670339.html
Copyright © 2011-2022 走看看