[LeetCode] 45. Jump Game II

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

  • 0 <= j <= nums[i] and
  • i + j < n

Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

Example 1:

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [2,3,0,1,4]
Output: 2

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 1000

跳跃游戏 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]。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意跟版本一很接近,唯一不同的是版本一是问是否能到达终点;版本二问的是跳到最后一个位置最少需要几步(题目给的 testcase 一定能到达终点)。

思路也是贪心,但是这个题跟一般的贪心略有不同。我参考了这个帖子。因为这里求的不是每一次最远能跳几步,而是每次在可跳范围内选择可以使得跳的更远的位置

注意代码中 for 循环停下的位置,在遍历数组时,我们不访问最后一个元素,这是因为在访问最后一个元素之前,我们的边界一定大于等于最后一个位置,否则就无法跳到最后一个位置了。如果访问最后一个元素,在边界正好为最后一个位置的情况下,我们会增加一次「不必要的跳跃次数」,因此我们不必访问最后一个元素。

时间O(n)

空间O(1)

end 表示每次能跳到的坐标,maxPosition 存放能跳到的最远距离,steps 记录跳的步数

maxPosition 很好理解,只是在不断更新能跳到的最远距离;遍历数组,当 i == end 的时候,意味着遍历到了当前能跳到的最远距离,此时一定需要再跳了所以需要加一步。

JavaScript实现

复制代码
 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var jump = function (nums) {
 6     let end = 0;
 7     let maxPosition = 0;
 8     let steps = 0;
 9     for (let i = 0; i < nums.length - 1; i++) {
10         maxPosition = Math.max(maxPosition, nums[i] + i);
11         if (i === end) {
12             end = maxPosition;
13             steps++;
14         }
15     }
16     return steps;
17 };
复制代码

 

Java实现

复制代码
 1 class Solution {
 2     public int jump(int[] nums) {
 3         int maxPosition = 0;
 4         int end = 0;
 5         int steps = 0;
 6         for (int i = 0; i < nums.length - 1; i++) {
 7             maxPosition = Math.max(maxPosition, i + nums[i]);
 8             if (i == end) {
 9                 end = maxPosition;
10                 steps++;
11             }
12         }
13         return steps;
14     }
15 }
复制代码

 

LeetCode 题目总结

posted @   CNoodle  阅读(423)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示