跳跃游戏 II
给定一个长度为 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 步到达数组的最后一个位置。
解题思路
- 1、使用贪心算法,遍历数组,维护当前可到达的最远位置和当前步数。
- 2、在遍历过程中,更新当前可到达的最远位置,即对于当前位置i,最远可到达的位置为i + nums[i]。
- 3、在每一步中,假设当前步数能够到达的范围为[start, end],选择在[start, end]范围内能够使得下一步跳得最远的位置。
- 4、在确定下一步的位置后,将步数加1,然后将end更新为当前可到达的最远位置。
- 5、直到end大于或等于目标位置nums.length - 1时,返回步数即可。
java实现
public class JumpGameII {
public int jump(int[] nums) {
int n = nums.length;
int maxPosition = 0; // 当前能够到达的最远位置
int end = 0; // 当前跳跃的边界
int jumps = 0; // 跳跃次数
for (int i = 0; i < n - 1; i++) { // 遍历数组,最后一个位置不需要跳跃
maxPosition = Math.max(maxPosition, i + nums[i]); // 更新当前能够到达的最远位置
if (i == end) { // 如果当前位置到达上一次跳跃的边界
end = maxPosition; // 更新边界为当前能够到达的最远位置
jumps++; // 跳跃次数加一
if (end >= n - 1) { // 如果边界已经大于等于数组的最后一个位置
break; // 跳出循环
}
}
}
return jumps;
}
public static void main(String[] args) {
JumpGameII solution = new JumpGameII();
int[] nums = {2, 3, 1, 1, 4};
System.out.println("Minimum jumps: " + solution.jump(nums)); // Output: 2
}
}
时间空间复杂度
-
时间复杂度:遍历一次数组,时间复杂度为O(n),其中n为数组nums的长度。
-
空间复杂度:仅使用了常数级的额外空间,空间复杂度为O(1)。