leetcode——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.

思路一:

该题可以使用阶段性思想即意味着适用DP去求解,属于非常简单的DP题目了。

首先,看能否达到A[0],这是肯定的。在到达A[0]的基础上,看能否到达A[1],而这要看从A[0]能否到A[1],即该元素之是不是够大。

适用B数组来记录A的跳转情况(true || false)

那么可知道状态转移公式:B[j] = (B[j-1] && A[j-1]>=1)||(B[j-2] && A[j-2]>=2)||(B[j-3] && A[j-3]>=3).......

以此类推。因此,该题的时间复杂度是O(n^2 )。

如果使用递归的话,该题的复杂度就高了。

AC代码:

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

思路二:


试想,如果在某一个时刻,能够到达的最远距离为i,那么是否意味着i之前的所有楼梯都能到达?

证明:

假设j<i,且j无法到达,则一定没有任何一条j之前的线路能够到达或跨越j,并到达j后面的任何点。

但i为可达,这与前面的结果相矛盾,因此,如果i可达,那么i之前的所有点都可达。


有了以上这个结论,就可以按照顺序遍历所有台阶,对每个台阶都求出最远到达的点。则最终最远可达点如果大于等于终点台阶,则

说明可以到达最终点;否则不可达。

该算法复杂度为O(n),比上一种思路更快,更好理解。

AC代码:

public class Jump_Game {
    
    public boolean canJump(int[] A){
        if(A==null ||A.length==0)
            return true;
        int end=0,current=0,farthest = A[0];
        int i=0;
        while(i<=farthest && i<=A.length-1){
            end = A[i]+i;
            if(end>farthest)
                farthest = end;
            i++;
        }

        if(farthest >= A.length-1)
            return true;
        else
            return false;
    }
    public static void main(String[] args){
        Jump_Game jump_game = new Jump_Game();
        int[] A = {2,3,1,1,4};
        System.out.println(jump_game.canJump(A));
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值