按顺序遍历数组,使用一个变量保存所遍历过的所有位置中能达到的最远位置,当数组下标大于所能达到的最远位置时,说明这个下标表示的位置不可达,即退出遍历并返回false
;当最远位置大于等于最后一个元素的下标时,说明可达,返回true
。
class Solution {
public boolean canJump(int[] nums) {
int max = 0;
for(int i=0; i<nums.length;i++){
if(i>max)break;
max = Math.max(max, i+nums[i]);
if(max >= nums.length-1){
return true;
}
}
return false;
}
}