Online Judge Solutions

Thursday, November 6, 2014

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.)

 
class Solution {
public:
  int jump(int A[], int n) {
        if (n <= 1) return 0;
        int current = 0;
        int reach = A[0];
        int jumps = 1;
       
        while(reach < n-1)
        {
            int maxReach = 0;
            for(int i = current+1; i <=reach; i++)
               maxReach = max(maxReach, i+A[i]);
            current = reach;
            reach = maxReach;
            jumps++;
        }
        return jumps;
    }
};

class Solution {
public:
  int jump(vector<int>& nums) {
        int n = nums.size();
        if (n <= 1) return 0;
        int current = 1;
        int reach = nums[0];
        int jumps = 1;
       
        while(reach < n-1)
        {
            int maxReach = 0;
            while(current <=reach) {
               maxReach = max(maxReach, current+nums[current]); 
               current++;
            }
            reach = maxReach;
            jumps++;
        }
        return jumps;
    }
};

No comments:

Post a Comment