Jump Game 116

Question

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.

Notice

This problem have two method which is Greedy and Dynamic Programming.

The time complexity of Greedy method is O(n).

The time complexity of Dynamic Programming method is O(n^2).

We manually set the small data set to allow you pass the test in both ways. This is just to let you learn how to use this problem in dynamic programming ways. If you finish it in dynamic programming ways, you can try greedy method to make it accept again.

Example

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Solution

DP: can[i]表示能否到达i点。初始化can[0]=true。对于每个点i,扫描其之前的所有点j,若j是可到达的(can[j]=true)并且A[j]+j>=i则i也是可到达的。

Greedy: 用farthest来记录能够到达的最远的点。扫描最远的点之前的所有点,如果A[j]+j>farthest,则更新最远的点。最后看最远的点是否能到达数组尾部。

代码如下:

DP

public class Solution {
    /**
     * @param A: A list of integers
     * @return: The boolean answer
     */
    public boolean canJump(int[] A) {
        // wirte your code here
        if(A == null || A.length == 0){
            return false;
        }

        boolean[] can = new boolean[A.length];
        can[0] = true;

        for(int i = 1; i < A.length; i++){
            for(int j = 0; j < i; j++){
                if(can[j] == true && A[j] + j >= i){
                    can[i] = true;
                    break;
                }
            }
        }

        return can[A.length - 1];
    }
}

Greedy

public class Solution {
    /**
     * @param A: A list of integers
     * @return: The boolean answer
     */
    public boolean canJump(int[] A) {
        // wirte your code here
        if(A == null || A.length == 0){
            return false;
        }

        int farthest = A[0];
        for(int i =1; i < A.length; i++){
            if(i <= farthest && A[i] + i > farthest){
                farthest = A[i] + i;
            }
        }

        return farthest >= A.length - 1? true : false;
    }
}

results matching ""

    No results matching ""