Tuesday, December 16, 2014

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.

1. O(N) time complexity and O(1) space complexity

class Solution {
public:
    bool canJump(int A[], int n) {
       
        int maxdist=0;
       
        for (int i=0; i<=maxdist&&i<n;i++)
        {
            maxdist = max(maxdist, i+A[i]);
        }
       
        return maxdist>=n-1;
    }
};

2. My original solution. O(N^2) time complexity

class Solution {
public:
    bool canJump(int A[], int n) {
        int i=0;
        int j=0;
        int newI, newJ;
        while(j<n-1)
        {
            j=i+A[i];
            if(j>=n-1)
              return true;
            int nextMax=j+A[j];
            newI=j;
            for (int k=i; k<j; k++)
            {
                if (k+A[k]>nextMax)
                {
                    nextMax=k+A[k];
                    newI = k;
                }
            }
           
            i=newI;
            if (nextMax==j)
               return false;
        }
       
        return true;
    }
};

No comments:

Post a Comment