Title:
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, then 3
steps to the last index.)
idea: This topic is similar to the jump game mentality. Only this time, we have to determine whether we can reach the end of the array (end point), and ask for the minimum number of hops. This time we still use "local optimal and global optimization", but the global optimization of this maintenance is divided into two variables: Step optimal and step-1 (assuming the current step is step), if our coordinates i Go to more than step-1 step furthest reached the position of Lastreach, that is step-1 step can not reach the current position I, then we update the steps, add step 1. What is difficult to understand here is that reach always maintains the furthest distance the step can reach, because reach = max (local, REACH) is not updated every time, only the furthest distance beyond the step range is updated, So when the step-1 step cannot reach the current position I, it is necessary to update Lastreach = reach and update the steps at the same time.
Complexity: Time complexity O (N), Space O (1)
Attention:
1. Be sure to determine whether you can reach the end point, if you cannot return 0, the problem does not indicate that the array must be able to reach the end point.
if (Reach < n-1) return 0; else return step;
2. Three maintenance variables, initialization starting from 0, because the reach of the first step depends on the a[0], should be updated together in the loop, otherwise the step and other variables will appear error.
int Lastreach = 0; int reach = 0; int step = 0;
AC Code:
Class Solution {public: int jump (int a[], int n) { if (n = = 0) return 0 ; int lastreach = 0; int reach = 0; int step = 0; for (int i = 0; i < n && i <= reach; i++) { if (i > Lastreach) { step++; Lastreach = reach; } reach = Max (a[i]+i, Reach); } if (Reach < n-1) return 0; else return step; }};
Dynamic planning When the interview is very important type, the general interview will not be too complex, mainly to examine the thinking and the boundary and other special circumstances of consideration, consider whether the problem is complete and comprehensive, focus on mastering a few classic topics, jump Game,maximum subarray, Maximum Product Subarray and so on, there is a subject.
[C + +] leetcode:104 Jump Game II (local optimal and global best method)