10/07/2012

Jump Game II

Jump Game II
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
 
Strategy: Greedy (reversed order)

Complexity: O(n^2)

public class Solution {
    public int jump(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (A.length == 1) return 0;
        int lastIndex = A.length - 1;
        int steps = 0;
        while (lastIndex > 0) {
            int preIndexMin = lastIndex;
            for (int i=lastIndex - 1; i>=0; i--) {
                if (A[i] >= lastIndex - i) {
                    if (preIndexMin > i) {
                        preIndexMin = i;
                    }
                }
            }
            if (lastIndex == preIndexMin) return -1;
            lastIndex = preIndexMin;
            steps++;
        }
        return steps;
    }
}

No comments:

Post a Comment