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.
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
题意:
思路:
以 [2,3,1,1,4]为例
可以想象一只青蛙,在每个刻度的石头上,弹跳力分别为2,3,1,1,4。青蛙是否能安全过河。
用maxReachIdx记录当前能跳的最远距离
指针i边扫边更新maxReachIdx
若maxReachIdx >= nums.length - 1 则返回true。
例子走一遍,先初始化指针 i= 0 , maxReachIdx = 0
当 i = 0 时,进入for循环,maxReachIdx更新为 3, 可以把红色部分看为青蛙可跳的势力范围
当 i = 4, maxReachIdx仍然为 3 则maxReachIdx < nums.length - 1 返回false 。
代码:
1 public boolean canJump(int[] nums) { 2 int maxReachIdx = 0; 3 for (int i = 0; i < nums.length && i <= maxReachIdx; i++){ 4 maxReachIdx = Math.max(maxReachIdx, i + nums[i]); 5 } 6 return maxReachIdx >= nums.length - 1; 7 }