Leetcode 55. Jump Game

本文探讨了两种解决数组中跳跃问题的方法:一种是简单的递归解决方案,但可能会导致时间限制超时;另一种则通过从后向前遍历数组,设置目标位置来优化路径寻找过程,实现了高效判断是否能到达最后一个元素的目标。

Simple recursion solution but got TLE.

public class Solution {
    private boolean isJump = false;
    
    public void canJumpRecur(int cur, int k, int[] nums) {
        if (cur == nums.length-1) { isJump = true; return; }
        for (int i=1; i<=k; i++)
            if (cur+i < nums.length)
                canJumpRecur(cur+i, nums[cur+i], nums);
    }
    
    public boolean canJump(int[] nums) {
        canJumpRecur(0, nums[0], nums);
        return isJump;
    }
}

Another approach. 

/**
 * Assume the length of the array is len, and the beginning target is len-1.
 * Then starting from len-2, 
 * if nums[len-2] + len-2 >= len-1 which means we can reach len-1 from len-2.
 * set len-2 as new target.
 * else check the previous index which is len-3.
 * finally if the target equals to 0 which means we can find a path from 0 to len-1.
 */ 
public class Solution {
    public boolean canJump(int[] nums) {
        int len = nums.length;
        int target = len-1;
        
        for (int i=len-2; i>=0; i--) 
            if (nums[i]+i >= target)
                target = i;
        
        return target == 0;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值