My Java solution using 3ms


  • 0
    P

    public class Solution {
    public int jump(int[] nums) {

        int maxJump = nums[0];
        int lastmax = nums[0];
        int maxi = 0;
        int maxIndex = nums.length-1;
        if(maxIndex==0)return 0;
        int count = 0;
        for(int i = 0;i<=lastmax;i++){
            if(i+nums[i]>maxJump){
                maxJump = i+nums[i];
                maxi = i;
            }
            if(i==lastmax){
                if(lastmax!=maxJump)count++;
                i = maxi;
                lastmax= maxJump;
                maxJump = lastmax;
            }
            if(lastmax>=maxIndex)return ++count;
        }
            return -1;
    
    }
    

    }


  • 0
    X

    You need check the non-reachable case, such as nums=[0,2], also get rid of the dead code (such as maxJump=lastmax) to make it concise.


  • 0
    P

    Thank you for your suggestion. I have modified the code.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.