LintCode : Jump Game

Problem description:

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.

Examples:

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

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

Solution 1:

public class Solution {
    /**
     * @param A: A list of integers
     * @return: The boolean answer
     */
    private boolean[] can;
    public boolean canJump(int[] A) {
        // wirte your code here
        if (A == null) {
            return false;
        }
        if (A.length == 0) {
            return true;
        }
        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] && (j + A[j] >= i)) {
                    can[i] = true;
                    break;
                }
            }
        }
        return can[A.length - 1];
    }
}
View Code

This is the dynamic programming version, the basic idea is that: the initialization is that I am in the first index of the array, so can[0] = true, then for every other index i, it's dependent on it's previous index, for all the previous index j, if can[j] = true, which means I can jump to this index j, and from this index j, I can jump A[j] steps, if (j + A[j]) >= i, which means I can get to index i from index j, then can[i] = true, then we can jump out this for loop. The time complexity of this algorithm is O(n*n).

Solution 2:

public class Solution {
    /**
     * @param A: A list of integers
     * @return: The boolean answer
     */
    private boolean[] can;
    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 && (i + A[i]) >= farthest) {
                farthest = i + A[i];
            }
        }
        return (farthest >= A.length - 1);
    }
}
View Code

This is the greedy version, the basic idea is that: I am in position 0 at first, so the farthest place I can jump to is A[0], then for all the index i from 1 to A.length - 1, if (i <= farthest), which means I can jump to this index i, and (i + A[i]), which is the farthest place I can jump to from this index i, if (i + A[i] >= farthest), then I refresh the farthest place I can go, finally I will get the maximum farthest from index 0, if it's bigger than A.length - 1, then I can get to the last index. The time complexity of this algorithm is O(n).

posted on 2016-05-21 15:37  dingjunnan  阅读(147)  评论(0编辑  收藏  举报

导航