Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is 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 and then steps to the last 3
index.)
Ideas:
Min Indicates the minimum number of jump required to reach the first node;
Maxreach indicates the farthest position that can be reached after the min jump;
Maxcanreach represents the furthest reachable position in the traversed node (i.e., a[i]+i);
When I>maxreach, it is explained that after the min jump is not enough to reach the node I, need to jump once more, and after the min+1 jump, the farthest can reach the position Manreach = Maxcanreach;
If Maxreach >=a.length-1, it means that at least the min jump can reach the end point.
The code is as follows:
Public intJumpint[] A) {if(A = =NULL|| A.length < 2) return0; if(a[0] = = 0) return0; if(A[0] >= a.length-1) return1; intmin = 1;//min Jump intMaxreach = a[0]; intMaxcanreach = a[0]; for(intI=1; i<a.length; i++) { if(I >Maxreach) {min++; Maxreach=Maxcanreach; } if(Maxreach >= a.length-1) { returnmin; } if(A[i] + i >Maxcanreach) Maxcanreach= A[i] +i; } returnmin; }
LeetCode-45 Jump Game II