Given an array of non-negative integers nums, 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.
You can assume that you can always reach the last index.
Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: 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.
Take the figure above as example, starting from the 0th, we first find all positions can be reached from the starting point (1st and 2nd in this case). Then, we check which of them can go further. In terms of the both, the 1st where is "3" can jump further. Thus we choose to jump to the 1st as the first time jump. In the next round, starting from the 1st, we can reach 2nd, 3rd and 4th. By comparison, we know that if we jump into the 4th, we will jump the farthest. Thus, we choose 4th to jump into.
func jump(nums []int) int {
var ans, pivot, maxFar int
for i := 0; i < len(nums)-1 && pivot < len(nums)-1; i++ {
if i+nums[i] > maxFar { // the farthest index can be reached from i
maxFar = i + nums[i]
}
if i == pivot { // reach the right boundary of last jump range
pivot = maxFar // start point of the next round of jump
ans++ // enter the `ans`th step
}
}
return ans
}