[LeetCode] 45. Jump Game II

跳跃游戏二。题意跟版本一很接近,唯一不同的是版本一是问是否能到达终点;版本二问的是跳到最后一个位置最少需要几步(应该是一定能到达终点的)。例子,

Example:

Input: [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.

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

时间O(n)

空间O(1)

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

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

 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 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12418133.html