Quick question about corner cases


  • 0

    I believe the logic is right, but it does not pass for 5 cases. One of them is

    Input:
    [2,5,0,0]
    Output:
    false
    Expected:
    true

    Why this one is true? It jump from index 0 to index 2, which is 0, which is the second to last index. It should be false,right? Could anyone give me a brief explanation? Really appreciate it!

    public class Solution {
        public boolean canJump(int[] nums) {
            if ( nums.length ==1 ) {return true;}
            for ( int i = 0; i < nums.length; ) {
                if ( i + nums[i] >= (nums.length-1) ) {return true;}
                else if (nums[i] == 0) {return false;}
                else { i = i + nums[i]; }
            }
            return false;
        }
    }
    

  • 1
    V

    "Each element in the array represents your maximum jump length at that position." , you can jump to nums[2] at most from index 0 (but you don't have to) . You could jump to nums[1] , then with 5 steps at hand(or rather foot) , you can reach the end .


Log in to reply
 

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