1. 题目
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 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.
2. 思路
第一个节点必须要进入,每次进入一个起点i之后,下一步的落点可以是[i+1, i+nums[i]],找到这个范围内的可以跳跃最远的点作为下一步。循环直到跳跃到最后。
3. 代码
耗时:13ms
class Solution {
public:
// 当做到第i步时,此时最大可以跳跃到的点时i+a[i];
// 下一步找到[i, i+a[i]]之间的最大可跳跃点, 下一步选择这个最大点
// 循环往复直到到最后一个点
int jump(vector<int>& nums) {
int sz = nums.size();
if (sz <= 1) { return 0; }
int k = 0;
int i = 0;
int i_max = 0;
while (i < sz - 1) {
k++;
int i_max = i + nums[i]; // 当前跳跃段的起点
if (i_max >= sz - 1) { break; }
int j_max = -1;
int j_max_idx = -1;
for (int j = i + 1; j <= i_max && j < sz; j++) { // 选择[i, i+nums[i]]段内的最大跳跃点作为下一点
int tmp_max = j + nums[j];
if (tmp_max > j_max) {
j_max = tmp_max;
j_max_idx = j;
}
}
i = j_max_idx;
}
return k;
}
};