跳跃游戏 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
步到达数组的最后一个位置。
示例 2:
输入: nums = [2,3,0,1,4] 输出: 2
提示:
1 <= nums.length <= 104
0 <= nums[i] <= 1000
- 题目保证可以到达
nums[n-1]
代码结果
运行时间: 64 ms, 内存: 15.9 MB
/*
* Problem: Given an array of non-negative integers nums, where each element represents the maximum jump length from that position. The goal is to reach the last index in the minimum number of jumps.
*
* Approach using Java Streams:
* Java Streams are generally used for functional operations on data. In this case, they are not ideal for such algorithmic implementation, but we can illustrate a conceptual approach.
*/
import java.util.stream.IntStream;
public class Solution {
public int jump(int[] nums) {
// Stream-based conceptual approach
// Variables are mutable inside streams
int[] jumps = {0}; // Number of jumps
int[] currentEnd = {0}; // End of the current range
int[] farthest = {0}; // Farthest we can reach
IntStream.range(0, nums.length - 1).forEach(i -> {
farthest[0] = Math.max(farthest[0], i + nums[i]); // Update farthest reach
if (i == currentEnd[0]) { // If current index is at the end of the jump range
jumps[0]++; // Increment jumps
currentEnd[0] = farthest[0]; // Update currentEnd
}
});
return jumps[0];
}
}
解释
方法:
这个题解使用贪心算法的思想。我们维护两个变量:当前能够到达的最远位置 `end`,和下一步能够到达的最远位置 `farthest`。在遍历数组的过程中,如果当前位置 `i` 超过了 `end`,说明我们必须再跳一步,并且将 `end` 更新为 `farthest`。这样,我们就能计算出到达最后一个位置所需的最小跳跃次数。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在更新`farthest`时使用`max(farthest, i + nums[i])`,而不是简单地将`farthest`设置为`i + nums[i]`?
▷🦆
算法中,如果`end`等于`i`时才增加跳跃次数并更新`end`为`farthest`,这种策略是否有可能导致在数组中的某些位置不被检查?
▷🦆
为什么在循环中不包括最后一个数组元素(即`range(n-1)`),达到数组的最后一个位置的条件是否在循环外处理?
▷🦆
在数组`nums`中如果存在多个零(例如`[3,2,1,0,4,0,0]`),这种贪心算法是否仍然有效,尤其是当零位于跳跃路径中时?
▷相关问题
跳跃游戏
给你一个非负整数数组 nums
,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标,如果可以,返回 true
;否则,返回 false
。
示例 1:
输入:nums = [2,3,1,1,4] 输出:true 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:
输入:nums = [3,2,1,0,4] 输出:false 解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
提示:
1 <= nums.length <= 104
0 <= nums[i] <= 105