55. Jump Game

55. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

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

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

My Solutions:

方法1: Brute Force, 用一个数组储存是否可以到达index i,在每一步都更新一下数组

方法2/3/4:Greedy

public boolean canJump(int[] nums) {

    // 方法1
    // boolean[] achievable = new boolean[nums.length];
    // achievable[0] = true;
    // for (int i = 1; i < nums.length; i++) {
    //     for (int j = 0; j < i; j++) {
    //         if (achievable[j] && (j + nums[j] >= i)) { // 原地可以到达,且位置i可以到达
    //             achievable[i] = true;
    //             break;
    //         }
    //     } 
    // }
    // return achievable[nums.length - 1];
    
    // 方法2:从前到后,用max记录可以到达的最大位置
    int max = nums[0];
    for (int i = 1; i < nums.length; i++) {
        if (max < i) return false;
        max = Math.max(max, nums[i] + i);
    }
    return max >= nums.length - 1;
    
    // 方法3:和方法2类似,从前到后,用max记录可以到达的最大位置
    int max = nums[0];
    for (int i = 1; i < nums.length; i++) {
        if (i <= max && i + nums[i] > max) max = i + nums[i];
    }
    return max >= nums.length- 1;
    
    // 方法4:从后到前,用last记录从后往前可以到达的位置
    int len = nums.length; 
    int last = len - 1;
    for (int i = len - 2; i >= 0; i++) {
        if (i + nums[i] >= last) last = i;
    }
    return last == 0;
}

Last updated