2014年4月16日 星期三

[LeetCode] Jump Game

Problem:
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.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Solution:O(n)
public class Solution {
    public boolean canJump(int[] A) {
        if(A==null || A.length == 0)
            return false;
        if(A.length ==1)
            return true;
            
        boolean ret = false;
        int require = 1;
        
        for(int i=A.length-2; i>0; i--){
            if(A[i] >= require )
                require = 1;
            else{
                require++;
            }    
        }
        return A[0] >= require;
    }
}

沒有留言:

張貼留言