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
.
思路分析:这题和Gas Station那题有些相似,但是更简单一些。这题可以用贪心法做,具体算法是我们可以从前向后遍历数组,计算当前可以jump到的最远的位置,遍历结束后,如果最远的位置大于等于A.length-1则返回true,否则返回false;但是要注意,如果中间出现0,那就一定要保证当前的upbound可以越过这个位置,否则即使可以到达这个位置也无法继续向前jump。但是也要考虑一个special case,就是最后一位恰好是0,此时可以刚好jump到这一位置停止,也成功。
AC Code
public class Solution {
public boolean canJump(int[] A) {
if(A.length == 1) return true;
int upbound = 0;
for(int i = 0; i < A.length; i++){
if(i + A[i] > upbound){
upbound = i + A[i];
}
if(A[i] == 0){
if(upbound <= i && i != A.length - 1) return false;
}
}
if(upbound < A.length - 1) return false;
return true;
}
}