Problem
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.
Example:
1 | |
Note:
You can assume that you can always reach the last index.
Explanation
-
If the input
numshas length less than or equal to 1, we return 0 immediately. -
We need to create variable
stepto represent how many jump,farthestto represent the farthest index we can jump,endto represent current jump’s ending index. All these variables are initialized to 0. -
Loop through the input array from index 0 to
len(nums) - 2inclusive, in every iteration, we update thefartheset = max(farthest, i + nums[i]). If current index hits theend, that means we need to jump, sostep += 1and updateendto be thefarthestwe have seen. -
Outside the loop, which means
ihits the last index, we can returnstepas the result.
Solution
1 | |