Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
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.
Note:
You can assume that you can always reach the last index.
跳跃游戏二。题意跟版本一很接近,唯一不同的是版本一是问是否能到达终点;版本二问的是跳到最后一个位置最少需要几步(应该是一定能到达终点的)。
思路也是贪心,但是这个题跟一般的贪心略有不同。因为这里求的不是每一次最远能跳几步,而是每次在可跳范围内选择可以使得跳的更远的位置。
时间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 }