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
.
记录每一步开始可跳的最大步数算进第一步中,即计算从第一步跳到任何一个可达的位置后又可接着跳到最远的距离。如果这个最远距离超过了到达最后一个index的长度 A.length - 1,则返回true,否则返回false。
Source
public boolean canJump(int[] A) {
int len = A.length;
int max = 0;
for(int i = 0; i <= max && i < len; i++){ // i <= max ***
if((A[i] + i) > max){
max = A[i] + i;
}
if(max >= len - 1) //从第一个跳到最后一个只需len - 1步
return true;
}
return false;
}
Test
public static void main(String[] args){
int[] num = {0,3,2,1};
boolean a = new Solution().canJump(num);
System.out.println(a);
}