给定一个非负整数数组nums,假定最开始处于下标为0的位置,数组里面的每个元素代表下一跳能够跳跃的最大长度。如果能够跳到数组最后一个位置,则返回true,否则返回false。
数据范围:
[2,1,3,3,0,0,100]
true
首先位于nums[0]=2,然后可以跳2步,到nums[2]=3的位置,再跳到nums[3]=3的位置,再直接跳到nums[6]=100,可以跳到最后,返回true
[2,1,3,2,0,0,100]
false
无论怎么样,都跳不到nums[6]=100的位置
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return bool布尔型
*/
public boolean canJump (int[] nums) {
// write code here
boolean[] canJump = new boolean[nums.length];
if (nums.length == 1) {
return true;
}
for (int i = nums.length - 2; i >= 0; i--) {
if (i + nums[i] >= nums.length - 1) {
canJump[i] = true;
} else {
for (int j = nums[i]; j >= 1; j--) {
if (canJump[j + i]) {
canJump[i] = true;
break;
}
}
}
}
return canJump[0];
}
} import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return bool布尔型
*/
public boolean canJump (int[] nums) {
// write code here
//最大跳远距离
int maxReach=0;
//循环维护最大跳转距离
for(int i=0;i<nums.length;i++){
//如果最大跳远距离无法到达该点为false
if(maxReach<i){
return false;
}
//如果最大跳远距离大等于目标位置为true
if(maxReach>=nums.length-1){
return true;
}
//遍历每个节点,只要该节点的跳远距离大于maxReach,就更新maxReach
maxReach=Math.max(maxReach,i+nums[i]);
}
return true;
}
} public boolean canJump (int[] nums) {
// write code here
int len = nums.length;
int end = 0;
for (int i = 0; i < len; i++) {
if (i > end) return false;
end = Math.max(end,i + nums[i]);
}
return true;
}