当前位置:网站首页>leetcode-45-跳跃游戏 II
leetcode-45-跳跃游戏 II
2022-08-09 00:27:00 【前端码农小王】
给你一个非负整数数组 nums ,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
示例 1:
输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
示例 2:
输入: nums = [2,3,0,1,4]
输出: 2
提示:
1 <= nums.length <= 1040 <= nums[i] <= 1000
解题思路
本题要我们求出调到输入数组最后一个位置所需的步数,想要求得调到最后一个位置所需的步数,就要在每次跳跃的时候跳的尽可能的远,那如何才能在每一步都跳的最远呢?根据题意可以每一个位置可以跳跃该位置整数的距离,所以我们应该在该范围内找一个下一次可以跳的最远的位置,也就是 i+nums[i] 最大。所以本题可以初始化一个 tail 指针指向当前所在位置,step 记录跳跃次数。当 tail+nums[tail] 小于 nums.length-1 时,不停向后跳跃,并且每一次找到下一次可以跳的最远的位置进行跳跃,并更新 tail 和 step,最后当 tail+nums[tail] >= nums.length-1,就说明已经到达了数组最后的位置,返回 step 即可。
代码实现
var jump = function(nums) {if(nums.length===1){return 0}let tail = 0let step = 1// 如果当前下标加上当前值达不到数组末尾位置,继续执行while(tail+nums[tail]<nums.length-1){let targetIndexlet max = 0// 每次在范围内找到可以跳的最远的位置跳for(let i = tail;i<=tail+nums[tail];i++){if(i+nums[i]>max){max = i+nums[i]targetIndex = i}}tail = targetIndexstep++}return step
}
至此我们就完成了 leetcode-45-跳跃游戏 II
如有任何问题或建议,欢迎留言讨论!
边栏推荐
- After the sessionStorage value is changed, the value obtained by the page using window.sessionStorage.getItem() will not be updated
- 《MySQL入门很轻松》第3章:数据库的创建与操作
- 控件限制总结
- Unity3D小白学习日记(01):如何把物体移动到鼠标点击处
- STM32H750VBT6 Keil5 error :flash download failed cortex-M7
- 2021 icpc 上海 H. Life is a Game
- 整流十二 -有效值、平均值、瞬时值、幅值的关系以及相关方法
- 【科研-学习-pytorch】2-线性回归
- win10出现次磁盘占用率百分之百的情况
- mysql在查询出来的数据前添加序号
猜你喜欢

Unified identity management platform IAM single sign-on process and third-party interface design scheme

注意:服务器

Non-major graduates, five-faced Ali: Four rounds of technical + HR have already taken an offer

Several ways to implement inheritance in js

GaN图腾柱无桥 Boost PFC(单相)五-细节处理

STM32H750VBT6 Keil5 error :flash download failed cortex-M7

一名双非程序媛面试蚂蚁、美团、携程等大厂拿 offer 分享面试过程

<力扣刷题>965. 单值二叉树

Early departure, learning source half a year, finally got the ants Offer to share the interview process

插值拟合——数据处理或预测
随机推荐
摘桃子(推式子+优化)
桌面内容整理,用时高效
笔记&代码 | 统计学——基于R(第四版) 第十一章 时间序列预测
ShadowMap-Example
【 StoneDB Class 】 introductory lesson 3: StoneDB installation of compilation
光照衰减-Lights
【科研-学习-pytorch】2-线性回归
#468. 函数求和
基本控件属性
STM32H750VBT6 Keil5 error :flash download failed cortex-M7
数学建模美赛题型分类
ScreenSpace-ShadowMap(屏幕空间的阴影映射技术)
三角果计数
最新豆瓣top250爬虫案例代码分析[注释齐全]
年初离职,学习半年源码,终于拿到了蚂蚁 Offer,分享面试过程
LeetCode每日一题(481. Magical String)
阿里云服务器买完不知道如何使用(新手入门教程)
Using MySQL in Ubuntu/Linux environment: Modify the database sql_mode to solve the "this is incompatible with sql_mode=only_full_group_by" problem
《MySQL入门很轻松》第3章:数据库的创建与操作
The difference between the apply and call in js and usage