55 Jump Game
https://leetcode.com/problems/jump-game/#/description
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
.
分析及代码
没什么要交代的,注意细节。
i <= reach
reach >= nums.length - 1
public boolean canJump(int[] nums) {
if(nums.length < 2) {
return true;
}
int reach = nums[0];
for(int i = 0; i < nums.length && i <= reach; i++) {
reach = Math.max(reach, i + nums[i]);
if(reach >= nums.length - 1) {
return true;
}
}
return false;
}
O(n)