leetcode 45/55. Jump Game/ 2(跳跃游戏)

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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

给一个数组,每个元素是能走的最大步数,问从index 0开始走的话能否到达终点,
和45题类似,但是45题要求给出具体步数,先写55,再写45

思路:
greedy
初始位置在index=0处,这是最开始我们能到达的地方,用canReach=0表示,
然后从0出发,往后面走,沿途不断更新能到达的地方,canReach = i + nums[i].
如果canReach >= n-1就说明能到达最后的index,直接返回true.
反之,如果遍历完了也不能到达最后的index,返回false.

45题只需要在 i==curEnd的条件里count++就行了

    public boolean canJump(int[] nums) {
        int n = nums.length;
        int canReach = 0;

        for(int i = 0; i <= canReach; i++) {
            int nextDest = i + nums[i];
            if(nextDest >= n-1) return true;
            canReach = Math.max(canReach, nextDest);
        }
        return false;
    }

45题代码

    public int jump(int[] nums) {
        int cnt = 0;
        int n = nums.length;
        int canReach = 0;
        int curMax = 0;

        for(int i = 0; i <= canReach; i++) {
            if(i == n-1) return cnt;
            canReach = Math.max(canReach, i+nums[i]);
            if(i == curMax) {
                cnt ++;
                curMax = canReach;
            }
        }
        return cnt;
    }
  • 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、付费专栏及课程。

余额充值