码迷,mamicode.com
首页 > Web开发 > 详细

45. Jump Game II(js)

时间:2019-02-24 01:21:17      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:imu   input   fir   nbsp   color   amp   array   @param   ini   

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)

标签:imu   input   fir   nbsp   color   amp   array   @param   ini   

原文地址:https://www.cnblogs.com/xingguozhiming/p/10424952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!