55. Jump Game & 45. Jump Game II

问题描述

  1. 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.
    Determine if you are able to reach the last index.
    For example:
    A = [2,3,1,1,4], return true.
    A = [3,2,1,0,4], return false.
  1. 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.
    For example:Given array A = [2,3,1,1,4]
    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.)
    Note:You can assume that you can always reach the last index.

问题分析

  1. 看到55题目我想到了动规、带记忆搜索,然而这两种做法都非常慢,即使加入了数组的预处理。参考了九章算法中的代码,解题思路为:遍历数组,维护当前可达最远的位置,当这个位置大于等于最后一个位置时,说明jump成功;当遍历的数组下标超过这个位置,说明当前位置已经不可达,jump失败。
    我咋这么蠢π_π
  2. 接着我做了45题,题的设定基本与55相同,不同的是此题要求的是最少跳数。我以为这下该用到动规/带记忆搜索了,结果还是慢成狗……参考了九章算法中的代码,解题思路为:记录一个p数组,p[i]代表的是到达i位置的最少跳数(p是非减的),其得到的方法为遍历nums数组,遍历到位置i时,将p数组中第一个未赋值位置到i+nums[i]之间的位置都赋为p[i]+1。这么做的依据在于,如果p[j]位置没有赋值,说明在前面i-1个位置都无法到达j位置,当下一个位置i可以到达j时,到达i的最小跳数p[i]加上从i到j的一跳,即为到j的最小跳数。

AC代码

55. Jump Game

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = len(nums)
        far = 0
        for i in range(n):
            if far >= n-1:
                return True
            if i > far:
                return False
            far = i + nums[i] if far < i + nums[i] else far
        return False

只要辣么短!Runtime: 60 ms, which beats 76.43% of Python submissions.
45. Jump Game II

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        p = [0]
        lp = 1
        for i in range(n-1):
            while i + nums[i] >= lp and lp < n:
                p.append(p[i] + 1)
                lp += 1
        return p[-1]

只要辣!么!短!Runtime: 68 ms, which beats 74.32% of Python submissions.

你可能感兴趣的:(55. Jump Game & 45. Jump Game II)