Tuesday, December 30, 2014

Jump Game (LeetCode Array)

Question: 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.

Idea: Greedy. Like climbing stairs, we can consider the general problem as if I reach a level "i", can I reach the level n=A.length. Assume we can successfully reach level i, we need to know the maximum reachable index from all the indices before i. Then we start at level i=1, for all the indices before this level, we find the maximum level we can reach. Finally we compare the maximum level we can reach with n, if the maximum level is above n, that means the last index is reachable.

Time: O(n) Space:O(1)

 public class Solution {  
   public boolean canJump(int[] A) {  
     int reach=1;  
     for(int i=0;i<reach&&i<A.length;i++)  
       reach=Math.max(reach,A[i]+i+1);  
     return reach>=A.length;  
   }  
 }  

No comments:

Post a Comment