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
nums
has length less than or equal to 1, we return 0 immediately. -
We need to create variable
step
to represent how many jump,farthest
to represent the farthest index we can jump,end
to represent current jump’s ending index. All these variables are initialized to 0. -
Loop through the input array from index 0 to
len(nums) - 2
inclusive, in every iteration, we update thefartheset = max(farthest, i + nums[i])
. If current index hits theend
, that means we need to jump, sostep += 1
and updateend
to be thefarthest
we have seen. -
Outside the loop, which means
i
hits the last index, we can returnstep
as the result.
Solution
1 |
|