Thursday, January 8, 2015

LeetCode 45: 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.)
public class Solution {
    public int jump(int[] A) {
        // Greedy algorithm
        // The kernel idea of greedy algorithm is to select an element that can reach the longest distance when given a fixed range.
        // Then update steps and fixed search range.
        int n = A.length;
        
        if (n <= 1)
            return 0;
            
        if (A[0] == 0)
            return 0;            
        
        int max = 0; // Max distance that can be reached.
        int id; // id when get max distance
        int range; // Search range
        int step = 1; // Number of steps
        
        int i = 0;
        
        while (i < n)  
        {
            id = -1;
            range = i+A[i];
            
            if (range >= n-1)
                break;
                
            while (i <= range)  
            {
                if (A[i]!=0 && max<i+A[i])
                {
                    max = i+A[i];
                    id = i;
                }
                
                i++;
            }
            
            // Can't reach the last element
            if (id == -1)
                return 0;
            
            step++;
            i = id;
        }
        
        return step;
    }
}

No comments:

Post a Comment