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:
First try: keep track of all possible paths. It makes the situation very complex.
Alternatively, check all points and record the furthest distance which we can make, and iterate all reachable indexes and update the furthest distance at the same time.
public class Solution {
public boolean canJump(int[] A) {
int last = A.length - 1;
int maxIndex = A[0];
for(int i = 1; i <= maxIndex && i <= last; i++){
if(A[i] + i > maxIndex){
maxIndex = A[i] + i;
}
}
return maxIndex >= last;
}
}
No comments:
Post a Comment