Leetcode55-jumping game

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

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

Determine if you can reach the last position.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: We can jump 1 step from position 0 to position 1, then jump 3 steps from position 1 to the last position.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: No matter what, you will always reach the index 3. But the maximum jump length of this position is 0, so you can never reach the last position.

At first glance, this question is to be realized by dynamic programming. I saw that the first idea after this question is to double traverse to determine whether each position can be reached. The idea is very simple. The code is as follows:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        vector<int> dp(nums.size(),0);
        if(nums.size()<2)return true;
        dp[0]=1;
        for(int i=0;i<nums.size();i++){
            if(dp[i]==0)continue;
            for(int j=0;j<=nums[i];j++){
                if(i+j>=nums.size()) continue;
                dp[i+j]=1;
            }
        }
        return dp[nums.size()-1]==1;
    }
};

But in some cases, it is overtime, this problem cannot be solved so violently. In fact, whether we can reach the middle position is not a matter of our concern. Where we can go the farthest is what we need to consider, so we use a data to store the maximum reachable position. If this position is behind the last one, then the last one It can be reached, and if a bit cannot be reached in the middle, it will directly exit. Each max update is also to compare the maximum distance that can be reached currently and the maximum distance that the array can reach.

class Solution {
public:
    bool canJump(vector<int>& nums) {
        if(nums.size()<2)return true;
        int max=0;
        for(int i=0;i<nums.size()-1;i++){
            if(max<i)break;
            max=max>(nums[i]+i)?max:(nums[i]+i);
        } 
        return max>=nums.size()-1;
    }
};

 

Published 17 original articles · liked 0 · views 3222

Guess you like

Origin blog.csdn.net/qq_31874075/article/details/105582975