LeetCode(055) Jump Game (Java)

本文探讨了一个利用动态规划解决跳跃游戏的问题,即在一个数组中,每个元素表示当前位置的最大跳跃距离,目标是判断是否能从数组的第一个位置跳到最后一个位置。通过分析两种动态规划方法,阐述了如何优化解决方案并避免超时问题。

题目如下:

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.


分析如下:

第一个版本

动态规划,O(N²)居然TLE了,囧

//TLE
public class Solution {
    public boolean canJump(int[] A) {
        boolean [] result = new boolean[A.length];
        if(A[0] > 0) {
            result[0] = true;
        }
        for (int i = 1; i < A.length; ++i) {
            for (int j =0; j < i; ++j) {
                if (result[j] && (j + A[j] >= i)) {
                    result[i] = true;
                    break;
                }
            }
        }
        return result[result.length - 1];
    }
}

第二个版本

类似动态规划,只是找到最终结果就跳出,所以只是有更大的概率比O(N²)好,worst case依然是O(N²)。 实现的时候有一些边界条件的BUG,记录如下:

// Input:   	[2,0,0]
// Output:	    false
// Expected:	true
//250ms
public class Solution {
    public boolean canJump(int[] A) {
        if (A.length == 0) return false;
        if (A.length == 1) return true;

        // BUG1: 
        // 错误地validate input
        // if (A.length ==0 || A[0] == 0) {
        //     return false;
        // }
        int maxIndex = A[0];
        for (int i = 0; i <= maxIndex; ++i) {
            if ((i + A[i]) > maxIndex) {
                maxIndex = (i + A[i]);
            }

            // BUG2 : reach the last index, means ">=" instead of ">"
            //if (maxIndex > A.length - 1) {
            if (maxIndex >= A.length - 1) {            
                return true;
            }
        }
        return false;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值