Topic:
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.)
Note:
You can assume so can always reach the last index.
Test instructions and Analysis: Using the greedy algorithm, each time to find the point can reach the maximum point Lastreach, if the Lastreach is greater than I, then recalculation can reach the maximum point, otherwise step+1, reset Lastsearch, recalculate the next maximum point can be reached.
Code:
classSolution { Public intJumpint[] nums) { if(Nums.length <= 1)return0; intreach = Nums[0];//record the maximum position that can be reached from the current point intLastreach = 0;//record the maximum points that can be reached before intStep = 0; for(intI=1;i<=reach && i<nums.length;i++){ if(I >Lastreach) {Step++; Lastreach=reach; } Reach= Math.max (Reach, i+Nums[i]); } if(Reach < Nums.length-1)return0; returnstep; }}
[Leetcode] 45. Jump Game II Java