问题描述
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.
思考:怎么才算停止?
想法
- 循环扫描A[i]数组,考虑截止到A[i]时能抵达的最远距离,如果最远距离为i且A[i]=0,停止,否则继续,直到maxTo >= len - 1(抵达最后一步时,必有maxTo >= len - 1);
代码
public class Solution {
public boolean canJump(int[] A) {
int len = A.length;
int maxTo = 0;
for(int i = 0; i < len; i++){
maxTo = maxTo > A[i] + i? maxTo: A[i] + i;
if(maxTo >= len - 1)
return true;
else if(maxTo == i)
break;
}
return false;
}
}