首页 > 代码库 > Leetcode-Jump Game II
Leetcode-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.)
1 public class Solution { 2 public int jump(int[] A) { 3 if (A.length==0 || A.length==1) return 0; 4 int len = A.length; 5 6 int[] stepMaxLen = new int[len+1]; 7 Arrays.fill(stepMaxLen, 0); 8 stepMaxLen[1] = A[0]; 9 if (stepMaxLen[1]>=len-1) return 1;10 for (int i=1;i<len;i++){11 int minStep = -1;12 for (int j=1;j<len+1;j++)13 if (i<=stepMaxLen[j]){14 minStep = j;15 break;16 }17 18 if (minStep==-1) return -1;19 20 if (i+A[i]>stepMaxLen[minStep+1]){21 stepMaxLen[minStep+1] = i+A[i];22 if (i+A[i]>=len-1) return minStep+1;23 }24 }25 26 27 return -1; 28 29 }30 }
Solution 2 (better solution):
In solution 1, we actually do need to use loop to find out the minStep to reach node i. We only need to maintain the maxReachLen of current number of steps, i.e., the last node that can be reached by using current number of steps, and the max reachable length at current node. Once we reach a node that is beyong the maxReachLen of current step, it means that now the node can only be reached by using one more step, we then update the current number of steps and the maxReachLen of current step.
NOTE: the principle of solution 1 and solution 2 is actually the same.
1 public class Solution { 2 public int jump(int[] A) { 3 if (A.length==0 || A.length==1) return 0; 4 int len = A.length; 5 6 int step = 1; 7 int maxStepReach = A[0]; 8 int maxReach = A[0]; 9 if (maxStepReach>=len-1) return step;10 for (int i=1;i<len;i++){11 if (maxReach<i) return -1;12 13 if (i>maxStepReach){14 step++;15 maxStepReach = maxReach;16 if (maxStepReach>=len-1) return step;17 }18 19 if (maxReach<A[i]+i) maxReach = A[i]+i;20 }21 22 return -1;23 }24 }
Leetcode-Jump Game II