给定一个长度为 n
的 0 索引 整数数组 nums
。初始位置在下标 0。
每个元素 nums[i]
表示从索引 i
向后跳转的最大长度。换句话说,如果你在索引 i
处,你可以跳转到任意 (i + j)
处:
0 <= j <= nums[i]
且i + j < n
返回到达 n - 1
的最小跳跃次数。测试用例保证可以到达 n - 1
。
代码:
cpp
class Solution {
public:
int jump(vector<int>& nums) {
int n=nums.size();
int current_end=0;//本次跳跃的最远位置
int fastest=0;//下次可以跳到的最远位置
int times=0;
if(n<=1) return times;
for(int i=0;i<n;++i)
{
fastest=max(fastest,i+nums[i]);
if(i==current_end)
{
current_end=fastest;
times++;
if(current_end>=n-1)
{
return times;
}
}
}
return times;
}
};
**解题思路:**使用贪心策略。用current_end记录本次跳跃可到的最远位置,记录每个位置可跳跃到的最远位置,用它们的最大值不断更新fastest。这样当i==current_end时,fastest的值就是本次跳跃中可到达的下次跳跃的最远位置,直接用fastest更新current_end,最终得到的times就是到达n-1位置的最小跳跃次数。
时间复杂度:O(n)
算法中只有一个 for 循环,遍历了数组一次(从索引 0 到 n-2)
循环内部的操作(比较、赋值等)都是常数时间 O (1)
因此整体时间复杂度为 O (n),其中 n 是数组 nums 的长度
空间复杂度:O(1)
算法只使用了有限的几个额外变量(jumps、current_end、farthest 等)
这些变量的数量与输入规模 n 无关,不随 n 的变化而变化
因此空间复杂度为常数阶 O (1)