您的位置:首页 > 其它

Leetcode-Jump Game

2014-11-17 07:04 441 查看
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
.

Have you met this question in a real interview?

Analysis:
We record the max reachable length and update it at each A[i].
1. If maxReach<i, then cannot reach i return false;
2. If maxReach<i+A[i], then we update the maxReach to i+A[i].
3. Once maxReach>=A.length-1, we can reach the end, return true.

Solution:

public class Solution {
public boolean canJump(int[] A) {
if (A.length==0 || A.length==1) return true;
int len = A.length;

int maxReach = A[0];
for (int i=1;i<len;i++)
if (maxReach<i)
return false;
else {
if (maxReach<i+A[i]) maxReach = i+A[i];
if (maxReach>=len-1) return true;
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: