题目
给定一个长度为 n
的 0 索引整数数组 nums
。初始位置为 nums[0]
。
每个元素 nums[i]
表示从索引 i
向后跳转的最大长度。换句话说,如果你在 nums[i]
处,你可以跳转到任意 nums[i + j]
处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1]
的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]
。
示例
示例 1:
输入: nums = [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。示例 2:
输入: nums = [2,3,0,1,4] 输出: 2
分析
贪心法
思路
初始化:
- 首先获取数组的长度
n
。若n
为 1,直接返回 0,因为已经在末尾。 - 初始化
jumps
为 0,currentEnd
为 0,farthest
为 0。
遍历数组:
- 在遍历过程中,对于每个位置
i
,计算i + nums[i]
,它代表从当前位置i
能跳到的最远索引。然后使用std::max
函数更新farthest
,确保farthest
始终是当前位置及其之前位置能跳到的最远位置。 - 当
i
等于currentEnd
时,意味着已经到达了当前这一跳的边界,此时需要进行一次新的跳跃,所以jumps
加 1,并且将currentEnd
更新为farthest
,也就是下一次跳跃的边界。
返回结果:
- 遍历结束后,
jumps
就是到达数组末尾所需的最少跳跃次数,将其返回。
时间复杂度:O(),
是数组的长度
空间复杂度:O(1)
class Solution {
public:
int jump(std::vector<int>& nums) {
int n = nums.size();
if (n == 1) {
return 0;
}
int jumps = 0;
int currentEnd = 0;
int farthest = 0;
for (int i = 0; i < n - 1; ++i) {
// 更新从当前位置能跳到的最远位置
farthest = std::max(farthest, i + nums[i]);
// 当到达当前跳跃的边界时
if (i == currentEnd) {
// 进行一次跳跃
jumps++;
// 更新下一次跳跃的边界
currentEnd = farthest;
}
}
return jumps;
}
};