Monday, March 4, 2013

[LeetCode] Jump Game

Thought:
Use an array to store how far you can go from index i. If it is less than zero, it means we could not reach index i.
To go to index i + 1, we could reach i first, or directly leave from some point before i.

Code:
public class Solution {
    public boolean canJump(int[] A) {
        int len = A.length;
        int[] step = new int[len];
        step[0] = 0;
        for (int i = 1; i < len; i++) {
            step[i] = Math.max(step[i - 1], A[i - 1]) - 1;
            if(step[i] < 0) return false;
        }
        return step[len - 1] >= 0;
    }
}

No comments:

Post a Comment