贪心算法,每一步都记录下能到达的最远位置,如果最远位置大于等于了数组最后一个位置即可到达
public class Test55 {
@Test
public void test() {
System.out.println(canJump(new int[] { 2, 3, 1, 1, 4 }));
System.out.println(canJump(new int[] { 3, 2, 1, 0, 4 }));
}
// [2,3,1,1,4]
public boolean canJump(int[] nums) {
int farthest = 0;
for (int i = 0; i < nums.length; i++) {
if (i <= farthest) {
farthest = Math.max(i + nums[i], farthest);
}
if (farthest >= nums.length - 1) {
return true;
}
}
return false;
}
}