您的位置:首页 > 其它

LeetCode 98 Jump Game

2014-10-27 20:23 351 查看
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.

分析:

维护一个从当前能往后跳得最大步数step,随着遍历更新,如果step直到最后都大于0,那么说明可以,只要遇见step<=0的情况,即可停止。

public class Solution {
public boolean canJump(int[] A) {
if(A==null || A.length==0)
return false;
int step=A[0];//记录从当前开始能往后跳得步数
for(int i=1; i<A.length; i++){
if(step>0){
step--;//往前跳一步减1
step = math.Max(step, A[i]);
}else
return false;
}
return true;//直到最后step还大于0,说明可以跳到最后
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Jump Game