55. 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.

这题限制了非负元素,我一开始的思路判断就是什么情况下才蹦不到最后一个位置,那就是在0的地方卡住了,毕竟即使所有都是1,也能一步步走到最后,只有前面的步数不够大,跨不过0,到0就卡住了。所以我给出的解法是先线性扫描,遇到0停下来,判断这个0之前的这一段能否跨过0。

方法一:找到决定性条件进行判断
bool canJump(vector<int>& nums) {
    int i, j, max_step = 0;
    for (i = 0; i < nums.size(); i++) {
        if (nums[i] == 0) {
            for (j = i - 1; j >= 0 && nums[j] != 0; j--) {
                max_step = max(max_step, j + nums[j]);
            }
            if (max_step == i && i == nums.size() - 1) return true;
            if (max_step <= i) return false;
        }
    }
    return true;
}
方法二: 动态规划法

其实两种方法差不多。这种是经典的动态规划问题,不停的计算局部最优解,更新全局最优解,然后判断。

  1. 能跳到位置i的条件:i<=maxIndex。
  2. 一旦跳到i,则maxIndex = max(maxIndex, i+A[i])。
  3. 能跳到最后一个位置n-1的条件是:maxIndex >= n-1

代码为:

bool canJump(int A[], int n) {
    int maxIndex = 0;
    for(int i=0; i<n; i++) {
        if(i>maxIndex || maxIndex>=(n-1)) break;
        maxIndex = max(maxIndex, i+A[i]);
    } 
    return maxIndex>=(n-1) ? true : false;
}

两种效率其实差不多,都是线性O(n).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值