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.)
greedy algorithm: O(n)
public class Solution {
public int jump(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A==null||A.length<=1) return 0;
int step=0,i=0,max=0,tmp=0;
while(i<A.length-1){
max=0;
for(int j=i+1;j<A.length&&j<=i+A[i];j++)
if(j+A[j]>=max||j+A[j]>=A.length-1){ max=j+A[j];tmp=j;}
i=tmp;
step++;
}
return step;
}
}
a little bit optimization to make worst case O(n)
public class Solution {
public int jump(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A==null||A.length<=1) return 0;
int step=0,i=0,max=A[0],tmp=0;
while(i<A.length-1){
for(int j=i+1;j<A.length&&j<=max;j++)
if(j+A[j]>=tmp||j+A[j]>=A.length-1){ tmp=j+A[j];}
i=max;
max=tmp;
step++;
}
return step;
}
}