官方给的贪心
public static boolean canJump1(int[] nums) {
int lastPos = nums.length - 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (i + nums[i] >= lastPos) {
lastPos = i;
}
}
return lastPos == 0;
}
视频弄得代码
public static boolean canJump(int[] nums) {
int [] index = new int[nums.length];
int jump = 0;
for (int i = 0; i <nums.length ; i++) {
index[i] = i+nums[i];
}
int maxIndex =0;
while (jump<index.length && jump <= maxIndex){
if (maxIndex< index[jump]){
maxIndex = index[jump];
}
jump++;
if(jump == index.length)
return true;
}
return false;
}
public static boolean canJump(int[] nums) {
int start = 0;
int end = 0;
while (start <= end && end < nums.length - 1) {
end = Math.max(end, nums[start] + start);
start++;
}
return end >= nums.length-1;
}