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楼开始的,只要判断能到达的最高楼是不是大于等于nums.leng-1就行
注意必须将循环的条件设置在i<=maxreach;因为如果i>maxreach,可以理解到此i楼是到不了的,后面的就不用说了
代码如下(已通过leetcode)
public class Solution {
public boolean canJump(int[] nums) {
int maxreach=0;
int i;
for(i=0;i<nums.length&&i<=maxreach;i++) {
maxreach=Math.max(i+nums[i], maxreach);
}
if(maxreach>=nums.length-1) return true;
else return false;
}
}