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 =
A =
[2,3,1,1,4]
, return true
.
A =
[3,2,1,0,4]
, return false
.
Solution:
It is very similar to 45. Jump Game II
Instead of return the steps required to reach the end, this problem require to return if it is possible to reach the end of the array.
Using a variable maxReach to keep tracking the maximum reachable index, if i reach the maxReach but can't move further and maxReach< endIndex, then it is not possible to reach the end. Actually, if it is not reachable, A[maxReach] must be 0.
Time complexity: O(n)
public boolean canJump(int[] A) {
if(A==null || A.length==0) return false;
int maxReach=0;
for(int i=0;i<A.length && i<=maxReach;i++){
maxReach=Math.max(i+A[i],maxReach);
}
return maxReach>=A.length-1;
}
No comments:
Post a Comment