首页 > 代码库 > Jump Game

Jump Game

Note:
From back to start, if A[distance] is larger than the distance to the last element, it indicates that the last element is reachable. We can move the last element to the previous one. Otherwise, keep adding the distance and compare A[distance] till distance to the first element. 

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;
        }
        
        if (A[0] == 0 && A.length == 1) {
            return true;
        }
        
        int n = A.length;
        int dis = 1;
        int i = n - 1;
        
        while (i >= 1 && i >= dis) {
            if (A[i - dis] >= dis) {
                dis = 1;
                i--;
            } else {
                dis++;
            }
        }
        
        if (i == 0 && A[i] != 0) {
            return true;
        }
        return false;
    }
}

 

Jump Game