[leetcode] 45. Jump Game II

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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.

Example:

Input: [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.

Note:

You can assume that you can always reach the last index.

分析

题目的意思是:给你一个数组,数组位置上的数代表能够走的最大长度,现在的目标是用最小的次数走到终点。

  • 贪心法,我们遍历当前跳跃能到的所有位置,然后根据该位置上的跳力来预测下一步能跳到的最远距离,贪心出一个最远的范围,一旦当这个范围到达末尾时,当前所用的步数一定是最小步数。
  • 我们需要两个变量curReach和maxReach分别来保存当前的位置和能到达的最远位置,用count来记录走的次数。
  • 如果位置i大于当前的位置最且小于能够到达的最远位置,说明我们要继续走,count++,把当前的位置置为能够到达的最大位置,然后每次最大位置都更新即maxReach=max(maxReach,i+nums[i])。
  • 最后,如果题maxReach没有到达末尾,返回-1,

C++实现

class Solution {
public:
    int jump(vector<int>& nums) {
        int curReach=0;
        int maxReach=0;
        int count=0;
        int i=0;
        int m=nums.size();
        while(i<m&&i<=maxReach){
            if(i>curReach){
                count++;
                curReach=maxReach;
            }
            maxReach=max(maxReach,i+nums[i]);
            i++;
        }
        if(maxReach<m-1){
            return -1;
        }
        return count;
    }
};

Python实现

class Solution:
    def jump(self, nums: List[int]) -> int:
        # max_reach = max(max_reach, i+nums[i])
        # if cur_reach<i count+=1

        n= len(nums)
        max_reach = 0
        cur_reach = 0
        res = 0
        for i in range(n):
            if cur_reach<i:
                cur_reach=max_reach
                res+=1
            max_reach = max(max_reach, i+nums[i])
        return res

下面是另一种实现,跟上面的思路一样:

class Solution:
    def jump(self, nums: List[int]) -> int:
        # max_reach = max(max_reach, i+nums[i])
        # if cur_reach<i count+=1
        max_pos = 0
        cur_pos = 0
        res = 0
        for i in range(len(nums)-1):
            max_pos = max(nums[i]+i,max_pos)
            if cur_pos==i:
                cur_pos = max_pos
                res+=1
        return res

参考文献

[编程题]jump-game-ii
[LeetCode] Jump Game II 跳跃游戏之二

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值