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 =[2,3,1,1,4]
The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index.)
class Solution { public: int jump(vector<int>& nums) { int step = 0; //当前跳数 int curMax = 0; //当前可达到的最远距离 int preMax = 0; //上一跳可达到的最远距离 for(int i=0;i<nums.size();i++){ if(curMax<i) //当前可达到的最大距离到不了i,所以返回-1 return -1; if(preMax<i){ //上一跳可达到的最大距离到不了i,所以要跳一步,更新step和preMax step++; preMax=curMax; } curMax=max(curMax,i+nums[i]); //记录可到达的最大距离 } return step; } };