10/07/2012

Jump Game

Jump Game
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.
Strategy: For each '0' in the array, find if it could be jumped over from its previous indexes, or if we can directly jump to the end.

Complexity: O(n^2)?

public class Solution {
    public boolean canJump(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int end = A.length - 1;
        for (int i=0; i<A.length; i++) {
            if (A.length != 1 && A[i] == 0 && i != end) {
                int nextNonZeroIndex = i+1;
                while (nextNonZeroIndex < end) {
                    if (A[nextNonZeroIndex] > 0) {
                        break;
                    }
                    else {
                        nextNonZeroIndex++;
                    }
                }   //max: end
                int j = i - 1;
                boolean continueSearch = false;
                while (j>=0) {
                    if (A[j] >= end - j || A[j] >= nextNonZeroIndex - j) {
                        continueSearch = true;
                        break;
                    }
                    j--;
                }
                if (!continueSearch)
                    return false;
            }
            
        }
        return true;
    }
}

No comments:

Post a Comment