55. Jump Game/45. Jump Game II

  1. 55. Jump Game
    思路:[greedy] 得到所能走到的最大距离,与最终结果比较
class Solution:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        max_nums=nums[0]
        x=0
        while x<min(max_nums+1,len(nums)):
            if nums[x]+x>max_nums:max_nums=nums[x]+x
            x+=1
        return max_nums>=len(nums)-1
 

下面的思路更清晰

class Solution:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        #greedy reach最远可达的位置
        reach = 0
        for i in range(len(nums)):
            #reach = max(reach, i+nums[i])
            if i > reach or reach >= len(nums)-1:
                break
            reach = max(reach, i+nums[i])
        return reach >= len(nums)-1
  1. 45. Jump Game II
    思路:算出第一步最远距离,第二步最远距离,直到符合要求,
# 45. Jump Game II
# 
class Solution:
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==1:return 0

        # 步数
        steps=1
        # 每一步所能到达的最远
        max_reach=nums[0]
        # 每一个位置所能到达最远
        step_reach=nums[0]

        x=0
        while x<len(nums):
            # 切换步数条件
            if max_reach<x:
                steps+=1
                max_reach=step_reach
            step_reach=max(step_reach,x+nums[x])

            x+=1
            
            if max_reach>len(nums)-2:return steps
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值