[leetcode]55. Jump Game青蛙跳(能否跳到终点)

时间:2023-02-12 14:33:54

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]为例

[leetcode]55. Jump Game青蛙跳(能否跳到终点)

可以想象一只青蛙,在每个刻度的石头上,弹跳力分别为2,3,1,1,4。青蛙是否能安全过河。

用maxReachIdx记录当前能跳的最远距离

指针i边扫边更新maxReachIdx

若maxReachIdx >= nums.length - 1 则返回true。

例子走一遍,先初始化指针 i= 0 , maxReachIdx = 0

[leetcode]55. Jump Game青蛙跳(能否跳到终点)

当 i = 0 时,进入for循环,maxReachIdx更新为 3, 可以把红色部分看为青蛙可跳的*范围

[leetcode]55. Jump Game青蛙跳(能否跳到终点)

当 i = 4,  maxReachIdx仍然为 3 则maxReachIdx  < nums.length - 1 返回false 。

代码:

   public boolean canJump(int[] nums) {
int maxReachIdx = 0;
for (int i = 0; i < nums.length && i <= maxReachIdx; i++){
maxReachIdx = Math.max(maxReachIdx, i + nums[i]);
}
return maxReachIdx >= nums.length - 1;
}