LeetCode 45. Jump Game II

题目描述

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.

解题思路

看到题目第一感觉是用递归!但是一看输入的 scale,感觉递归有可能超时。百度一下,看到 “贪心” 二字,有了点思路,但是我再一看别人的代码,感觉不是很好理解。于是自己写吧,现将规律奉上:对于每一次选择,选取最有潜力的那一个位置。潜力的含义在于这个位置能带来的下一步的收益,从本题来看,收益在于可以走到的距离。理解了这个,请看下面的代码。

代码

class Solution:
    def jump(self, nums: List[int]) -> int:
        if len(nums)  < 2:
            return 0
        cur = 0
        ans = 0
        while 1 # 坚信一定有 break:
            cur_max_reach = cur + nums[cur] #当前位置可以辐射的范围
            if cur_max_reach >= len(nums) - 1: # 如果可以辐射到最后一个则退出
                ans += 1  # 切记这一步添加
                break           
            next_max_reach = cur + nums[cur] # 辐射范围内的最大潜力
            next_pos = cur_max_reach  # 最大潜力位置就是下一步 cur 的值
            for i in range(cur + 1, cur + nums[cur] + 1):
                if i + nums[i] > next_max_reach:
                    next_max_reach = i + nums[i]
                    next_pos = i
            cur = next_pos
            ans += 1 # 走一步
        return ans 
            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值