【leetcode刷题】45 & 55 jump game & jump game 2

原题链接
https://leetcode.com/problems/jump-game/
https://leetcode.com/problems/jump-game-ii/
解题思路
两道题思路类似,都是用贪心算法。记录下跳i步时可以跳过的最大距离。但是注意,在确定第i+1步的最远距离时,需要考虑所有i-1步到i步之间范围起始点,跳两步寻找i+1步的最远距离。
对于jump game,当step数量大于最远距离值时,返回false
对于jump game 2,返回step数量
在这里插入图片描述
代码

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

猜你喜欢

转载自blog.csdn.net/weixin_39746008/article/details/89435592