45. Jump Game II(js)
Posted mingL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了45. Jump Game II(js)相关的知识,希望对你有一定的参考价值。
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; };
以上是关于45. Jump Game II(js)的主要内容,如果未能解决你的问题,请参考以下文章