LeetCode 45. 跳跃游戏 II
题目描述
给定一个长度为 n
的 0 索引整数数组 nums
。初始位置在下标 0。
每个元素 nums[i]
表示从索引 i
向后跳转的最大长度。换句话说,如果你在索引 i
处,你可以跳转到任意 (i + j)
处:
0 <= j <= nums[i]
且i + j < n
返回到达 n - 1
的最小跳跃次数。测试用例保证可以到达 n - 1
。
示例
示例 1:
输入: nums = [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2 。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
示例 2:
输入: nums = [2,3,0,1,4] 输出: 2
解法
1.贪心策略
解题思路
创建两个辅助变量 currentEnd
:当前跳跃能到达的最远位置,farthest
:在所有可选项中最远能到达的位置,遍历每个位置,不断更新能够到达的最远位置 farthest,
当到达 currentEnd
(当前跳跃的边界)时,必须进行一次跳跃,ans + 1,更新 currentEnd
为新的最远可达位置farthest,
如果已经能到达终点,提前结束循环。
在每一步的可达范围内,选择能跳得最远的点作为下一跳的起点,不是真正选择具体位置,而是通过维护 farthest
来隐式选择。因为每次都在当前能力范围内尽可能扩大下一次的跳跃范围,确保了用最少的跳跃次数达到最远的距离。
class Solution {
public:int jump(vector<int>& nums) {int ans = 0, n = nums.size();int currentEnd = 0, farthest = 0;for (int i = 0; i < n - 1; i++) {farthest = max(farthest, i + nums[i]);if (i == currentEnd) {ans++;currentEnd = farthest;if (currentEnd >= n - 1) {break;}}}return ans;}
};
时间复杂度O(N),空间复杂度O(1)