LeetCode OJ 之 Jump Game (“跳跃”游戏 - 一)

题目:

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.

给一个非负数组,假设你最开始位于数组的第一个下标处。数组中的每个元素表示在这个位置上可以跳的最远长度,判断你是否能够到达数组的最后位置。

For example:
A = [2,3,1,1,4], return true

A = [3,2,1,0,4], return false.

思路:

1、贪心算法:

1,若在任意pos位置出现maxJump为0的情况,则说明无法继续向前移动,返回false。

2.若在任意pos位置出现maxJump +pos >= n - 1 说明可以完成最后一跳,返回true。

代码1:

class Solution {
public:
    bool canJump(int A[], int n) 
    {
        if(n == 0 || n == 1)
            return true;
        int maxJump = A[0];
        for(int i = 1 ; i < n ; i++)
        {
            if(maxJump == 0)
                return false;
            maxJump--;
            //贪心选择
            if(maxJump < A[i])
            {
                maxJump = A[i];
            }
            if(maxJump + i >= n-1)
                return true;
        }
    }
};

由于每层最多可以跳 A[i] 步,也可以跳 0 或 1 步,因此如果能到达最高层,则说明每一层都可以到达。有了这个条件,说明可以用贪心法。

思路一:正向,从 0 出发,一层一层网上跳,看最后能不能超过最高层,能超过,说明能到达,否则不能到达。
思路二:逆向,从最高层下楼梯,一层一层下降,看最后能不能下降到第 0 层。

代码2:

class Solution {
public:
    bool canJump(int A[], int n) 
    {
        int maxReach = 0;//maxReach表示能到达的最远pos(下标)
        //循环结束条件1、i > maxReach 表明不可能到达尾部,因为最远连i都到不了,更不可能到达比i更远的结尾
        //循环结束条件2、maxReach >= n-1 表明已经能到达尾部,结束循环
        for(int i = 0 ; i <= maxReach && maxReach < n-1; i++)
        {
            maxReach = max(maxReach , i + A[i]);//比较最远点和当前i可以到达的最远点,取较大值
        }
        return maxReach >= n-1;
    }
};

代码3:

class Solution {
public:
    bool canJump(int A[], int n) 
    {
        if(n == 0 || n == 1)
            return true;
        int maxReach = n-1;
        
        for(int i = n-2 ; i >= 0 ; i--)
        {
            if(i + A[i] >= maxReach)//判断i能否到达maxReach,如果能到达,把i设为目标位置,继续判断前面是否能到达目标位置i,直到目标位置变为0,说明可以到达
                maxReach = i;
        }
        return maxReach == 0;
    }
};




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值