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.
For example:
Given array A =
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, then 3
steps to the last index.)
Solution:
Loop the array, record the maximum index, which 0...i can reach to in ONE step. MAX = max(j+num[j]), 0<=j<=i.
Index 0 can reach to num[0]. Suppose the maximum index 0...num[0] can reach to is M in ONE step. If M >= last index, the minimum steps is 2. Else, when we move to M, and get the maximum step 0...M can reach to, lets call it N. We know to reach N, we need minimum 3 steps. Repeat the process until get to the last index.
Loop the array, record the maximum index, which 0...i can reach to in ONE step. MAX = max(j+num[j]), 0<=j<=i.
Index 0 can reach to num[0]. Suppose the maximum index 0...num[0] can reach to is M in ONE step. If M >= last index, the minimum steps is 2. Else, when we move to M, and get the maximum step 0...M can reach to, lets call it N. We know to reach N, we need minimum 3 steps. Repeat the process until get to the last index.
class Solution { public: int jump(vector& nums) { int steps = 0; int maxCur = 0; int lastIndex = 0; for(int i=0;i<nums.size()-1;i++) { maxCur = max(maxCur, i+nums[i]); if(i == lastIndex) { steps++; lastIndex = maxCur; } } return steps; } };