【题目】
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;
}
};
本文介绍了一个算法问题,即如何在给定的非负整数数组中找到从起始位置到达最后一个元素所需的最少跳跃次数。通过贪心策略逆向计算,确保路径选择的效率。
2200

被折叠的 条评论
为什么被折叠?



