LeetCode Brushing Notes_55. Jumping Game

The topic is from LeetCode

55. Jumping Game

Other solutions or source code can be accessed: tongji4m3

description

Given an array of non-negative integers, you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine whether you can reach the last position.

Example 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。

Example 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

Ideas

//伪代码
int i=0;//所处位置
int jump=0;//能跳到的最远位置
while(i<=jump)
{
    
    
    jump=max(jump,i+nums[i]);//i+nums[i]为通过i位置能跳到的最远处
    if(jump>=nums.length-1) return true;
    ++i;//不断往前走一格
}
return false;

Code

public boolean canJump(int[] nums)
{
    
    
    int i = 0;//所处位置
    int jump = 0;//能跳到的最远位置
    while (i <= jump)
    {
    
    
        jump = Math.max(jump, i + nums[i]);//i+nums[i]为通过i位置能跳到的最远处
        if (jump >= nums.length - 1) return true;
        ++i;//不断往前走一格
    }
    return false;
}

Complexity analysis

time complexity

O (N) O (N) O ( N ) , only need to traverse the array once

Space complexity

O (1) O (1) O ( 1 ) , only two indexes

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108251306