题目描述:
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], returntrue.
A = [3,2,1,0,4], returnfalse.
解题思路:
- 这道题的意思是每个元素代表可以走的最大步数,能走到数组的结尾就返回 true,否则返回 false;
- 先说一下我的错误思路,我考虑了当前元素是 0 的情况,在这里其实不用考虑的
- 这道题考察的点是贪心算法,即每次都要走到最远处,因为既然能够走到最远处去,那么它的近处也是可以访问的
代码如下:
public boolean canJump(int[] A) {
int len = A.length;
int temp = 0;
// temp 表示是否可以到达当前的 i 位置
for(int i = 0; i < len; i++){
// 如果能够到达当前的位置 i ,而且当前位置能够达到的最远距离大于 temp,就对 temp 值进行更换
if(temp >= i){
if(A[i] + i > temp){
temp = A[i] + i;
}
}
}
if(temp >= len - 1) return true;
else return false;
}