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:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
Note: You can assume that you can always reach the last index.
解题思路:
- 模拟版(AC):最简单有效的办法就是模拟跳的过程,也就是模拟你用眼睛看那个示例的答案是怎么来的那个过程。具体细节见代码。
int jump(vector<int>& nums){
int n = nums.size();
if(n == 0 || n == 1)
return 0;
int maxPos = 0; // 下一跳能跳到的最远的位置
int currMax = 0; // 这一跳能到达的最远的位置
int ans = 0; // 需要跳的步数
// 模拟跳的过程
for(int i = 0;i < n; i++) {
maxPos = max(maxPos, nums[i]+i);
if(i < currMax) // 这里不能等于,因为maxPos已经更新到i了,当i == currPos时就必须进行下一跳的抉择了
continue;
else{
ans++;
currMax = maxPos;
if(currMax >= n-1) // 如果能跳到最后就可以直接退出了
break;
}
}
return ans;
}