My very simple Java solution


  • -3
    S

    This is worst case O(n^2), but will work fine unless confronted by bizarre inputs. The idea is to go through the array and when we find a 0 look for a number before it that can jump over it.

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

Log in to reply
 

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