题目:
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
.
解决:
难点是跳到值为0的位置,是不是最后一个位置。
public class Solution {
public boolean canJump(int[] A) {
int idx = 0;
while(true){
if (A[idx]+idx >= A.length || A[idx]==0 && idx==A.length-1)//跳过了,或最后一个是0
return true;
else if (A[idx]==0 && idx!=A.length-1)//跳到值为0的,但不是最后一个位置
return false;
else
idx +=A[idx];
}
}
}