题目描述
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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
解题思路
错误想法(最开始的想法):
一直以贪心策略从初始位置开始跳跃最大步数从0跳到A[0]位置,在从A[0]跳到A[0]+A[A[0]]看最终能否到达数组尾部,如果到达不了,则跳跃最大步数-1,依次类推,使用递归来实现。
简单可行的思路:
问题可以简单描述为,从0开始最远能走到哪?只要最大步数>=A.length - 1,就可以走到队尾。
代码
public static boolean canJump(int[] A) {
int len = A.length;
int maxStep = 0;
if(len==0)
return false;
for (int i = 0; i < len - 1; i++) {
if(maxStep >= i && i + A[i] > maxStep){
maxStep = i + A[i];
}
}
if(maxStep >= len - 1){
return true;
}
return false;
}