#leetcode#Jump Game

本文详细介绍了如何优化跳跃游戏算法,从使用动态规划的O(n^2)复杂度降低到贪心算法的O(n)复杂度。通过Codeganker大神的思路,我们探讨了如何更高效地解决此类问题,提供了关键的代码实现和分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


刚开始是用dp做的, boolean[] dp , 假设 i,j都是有效的index并且 i > j, 则 dp[i] = dp[j] && (nums[j] >= (i - j)), 也就是说能跳到 i 的前提是前面有一个点 j 可以跳到, 并且从 j 能够跳到 i,对于每一个点都要遍历前面的点看有无有效点j, 所以复杂度是 O(n^2), 在leetcode中会TLE

public class Solution {
    public boolean canJump(int[] nums) {
        if(nums == null || nums.length == 0){
            return false;
        }
        boolean[] dp = new boolean[nums.length];
        dp[0] = true;
        for(int i = 1; i < nums.length; i++){
            for(int j = 0; j < i; j++){
                dp[i] = dp[j] && nums[j] >= (i - j);
                if(dp[i] == true){
                    break;
                }
            }
        }
        
        return dp[nums.length - 1];
    }
}


然后学习了code ganker大神的思路, 我觉得是greedy, O(n)

public class Solution {
    public boolean canJump(int[] nums) {
        if(nums == null || nums.length == 0){
            return false;
        }
        int reach = 0;
        for(int i = 0; i <= reach && i < nums.length; i++){
            reach = Math.max(nums[i] + i, reach);
        }
        
        if(reach < nums.length - 1){
            return false;
        }
        return true;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值