Friday, May 3, 2013

Leetcode: Jump Game II in Java



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.)
The major difference between this and the previous one is. We need to do as small as possible jump. So in each step. We want to jump as fast as we can. This thing does not Change. We will add one step to our result and start next range when we go out of current range.  Otherwise, we will just calculate the max range we can get inside current range.

Solution:

public int jump(int[] A) {     
        int curMax = 0; int nextMax = 0; int ans = 0;
        for (int i = 0; i < A.length; i++) {
            if (i > curMax) {
                curMax = nextMax;
                ans++;
            }
            nextMax = Math.max(nextMax,A[i] + i);
        }
        return ans;
    }

No comments:

Post a Comment