My Solution fails for [2,5,0,0]


  • 0
    A

    [2,5,0,0] should return false, as per my understanding of the problem. How the expected answer is true ? Can someone please explain ? Here's y Java solution,

    public boolean canJump(int[] nums) {
        
        if(nums.length == 0 || nums == null)
            return false;
        
        if(nums.length == 1)
            return true;
        
        int jumpIndex = 0, jumpLen;
        int arrlen = nums.length;
        
        while(true){
            if(jumpIndex < arrlen){
                if(nums[jumpIndex] == 0 && jumpIndex != arrlen-1){
                    return false;
                }
                
                jumpLen = nums[jumpIndex];
                jumpIndex += jumpLen;
                
                if(jumpIndex == arrlen-1){
                    return true;
                }
            }else if(jumpIndex >= arrlen){
                return true;
            }
        }
    }

  • 1

    Each element in the array represents your maximum jump length at that position. You can jump 0, 1 or 2 at the first position.


  • 0
    A

    Sorry for asking this again (English is not my mother tongue) So when you say maximum jump at that position, does that mean I can jump forward from that position ?


  • 0

    Yes.
    You can jump to 0, 1 or 2 from 2 (2 choices)
    You can jump to 3, 4, 5, 6 or 7 from 5 (5 choices)
    And so on...


Log in to reply
 

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