分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

45. Jump Game II(js)

发布时间:2023-09-06 02:33责任编辑:傅花花关键词: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: 2Explanation: 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)

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved