LeetCode Jump Game 前跳游戏

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.

 

理解题意:

当前的A[i]值代表,当前能跳的最大值,并不是一定要跳这么远的,比如A[0]=3,那么我们可以跳0到3步。

这道题的关键:搞清楚结束条件。

注意这道题, LeetCode的测试有bug,那就是可以设定结束条件为:A[i] == 0 return false. 那样可以使用贪心法在LeetCode上AC。

但是明显这个是错误的,比如:{2,3,0,2,0,2};这个应该是真。

所以判定这里的判断结束条件应该是:

记录lastJump的位置,循环i到lastJump,所有位置,找出其中的最大值maxJump =max{ i+A[i]};如果这个区间内的最大值maxJump <= lastJump,那么就返回假,因为没有任何一个位置可以跳出这个位置。

如果没有这样的位置,一直可以跳到最后,那么就返回为真。

class Solution 
{
public:
    bool canJump(int A[], int n) {
		int maxJump = 0;
		int lastJump = 0;
		int i = 0;
		while (maxJump < n-1)
		{
			if (i+A[i] > maxJump) maxJump = i+A[i];
			if (i >= lastJump)
			{
				if (maxJump <= lastJump) return false;
				lastJump = maxJump;
			}
			i++;
		}
		return true;
	}
};


 

 2014-1-29 update

bool canJump(int A[], int n) 
    {
	    int last = 0;
	    int max_step = 0;
	    for (int i = 0; i < n-1; i++)
	    {
		    max_step = max(max_step, A[i]+i);
		    if (i == last)
		    {
			    if (max_step == i) return false;
			    last = max_step; //max_step = 0; 可以不重置,后面的数一定大于前面的
		    }
	    }
	    return true;
    }

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值