Title: |
Jump Game II |
Pass Rate: |
24.5 |
Difficulty: |
Difficult |
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.)
Greedy algorithm
Each time you walk through all the nodes that can reach the farthest distance, find the farthest node that can reach, and then continue to find,
One step at a distance.
1 Public classSolution {2 Public intJumpint[] A) {3 intStep=0,lastmax=0,max=0;4 for(inti=0;i<a.length;) {5 if(lastmax>=a.length-1) Break;6 while(i<=Lastmax) {7 if(i+a[i]>max) {8max=i+A[i];9 }Teni++; One } A if(lastmax<max) { -lastmax=Max; - } thestep++; - } - returnStep; - } +}
Leetcode------Jump Game II