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.
Example 1:
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
每个数组的数字代表它能跳的最大格数,求是否能到达终点。
遍历数组,第i个,用一个变量canReach保存前i - 1个是否能到达此处。如果可以,则判断此格子能否跳得更远,能则更新canReach。
class Solution {
public boolean canJump(int[] nums) {
int canReach = 0;
int i = 0;
for (;i <= canReach && i < nums.length; i++){
canReach = Math.max(canReach,i + nums[i]);
}
return i == nums.length;
}
}
425

被折叠的 条评论
为什么被折叠?



