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

java code : 这题初看用DP的思路很清晰: 设DP[i] := 从第 i 个位置开始能否到底最后一个位置,那么转移方程很好写

  dp[A.length - 1] = true; 看代码吧,不过会超时,因为复杂度是O(n^2)

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

下面给出一种O(n)的算法:

我们用maxlength 维护一个从开始位置能到达的最远距离,然后判断在当前位置是否能够到底最后一个位置和当前位置是否可达,如果两个条件都满足,那么返回true,如果当前位置是0,并且最远距离不能超过当前位置,那么只能返回false 了,更新最远距离

java code : 416ms 

public class Solution {
    public boolean canJump(int[] A) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(A.length <= 1)
			return true;
		if(A[0] >= (A.length - 1))
			return true;
		int maxlength = A[0];
		if(maxlength == 0)
		    return false;
		for(int i = 1; i < A.length - 1; i++)
		{
			if(maxlength >= i && (i + A[i]) >= A.length - 1)
				return true;
			if(maxlength <= i && A[i] == 0)
				return false;
			if((i + A[i]) > maxlength)
				maxlength = i + A[i];
		}
		return false;
    }
}

顺便说一下我看讨论区有人贴出如此算法并且还过了:

class Solution {
public:
    bool canJump(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
    int i = 0;
    while( i < n-1)
    {
        if( A[i] == 0)
            return false;
        i += A[i];  
    }
    return i >= n-1;
    }
    
};
这个算法是错误的,因为有一组反列: A = {5,4,0,0,0,0,0}, 显然应该返回 false.

leetcode 的数据还是有点弱。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值