【题目】
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.)
You can assume that you can always reach the last index.
【解】
从最后的位置往前推,贪心记录能到达这个位置的最靠前的一个的下标。
A = [2, 3, 1, 1, 4],对应的 V = [-1, 0, 0, 1, 1]
然后从后往前推,数几步能到第一个位置(-1)
求V:从第一个数开始,A[0] = 2,能到达的位置有0, 1和2,然后下一个数A[0] = 3,0, 1, 2这3个位置已经可以从位置0达到,所以从位置3开始看能否达到,然后给V赋值......
给V赋值的时候只顺序做了一次,所以时间复杂度应该是O(n)? ,空间复杂度O(n)
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
vector<int> v(n);
v[0] = -1;
int t = 0;
for (int i = 0; i < n; i++) {
int a = nums[i];
if (a + i > t) {
int j;
for (j = t + 1; j <= a + i && j < n; j++) {
v[j] = i;
}
t = j - 1;
}
}
int i = v[n - 1];
int cnt = 0;
while (i != -1) {
i = v[i];
cnt++;
}
return cnt;
}
};