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.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
方法一:从末尾开始查询 找出每次都能到达的 位置:
public boolean canJump(int[] nums) {
if(nums==null||nums.length==0) {
return false;
}
return can(nums,nums.length-1);
}
public boolean can(int [] nums,int endIndex) {
if(endIndex == 0 ) {
return true;
}
for(int index=endIndex-1;index>=0;index--) {
if(nums[index]+index>=endIndex && can(nums,index)) {
return true;
}
}
return false;
}
超时凉凉
方法二:判断每个能达到的最远位置 判断能否直接到达末尾 若在达到末尾之前 可走的最大步数小于0则 直接返回false
public boolean canJump(int[] nums) {
if(nums==null||nums.length==0) {
return false;
}
int step = 0;
for(int i=0;i<nums.length;i++) {
if(step <= 0 && i!=0) {
return false;
}else {
if(i+nums[i] > nums.length-1) {
return true;
}
//求出到达这一步后 还可继续行走的最大步数
step = Math.max(step-1, nums[i]);
}
}
return true;
}