45. Jump Game II
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.题意:以数组项的值作为步长,求出最短跳跃次数代码如下:
/** * @param {number[]} nums * @return {number} */ //上次跳:before,当前跳:curr,res:跳跃次数 var jump = function(nums) { var len=nums.length; var before=0; var curr=0; var res=0; for(var i=0;i<len;i++){ //前一跳无论如何不能到达终点或越过终点 if(i>curr){ return -1; } //继续向前跳 if(i>before){ before=curr; res++; } //记录当前跳能最远达到多远 curr=Math.max(curr,i+nums[i]) } return res; };
原文地址:https://www.cnblogs.com/xingguozhiming/p/10424952.html
时间: 2024-10-24 14:05:01