当前位置: 首页 > news >正文

【LeetCode 面试经典150题】45. Jump Game II 跳跃游戏II

45. Jump Game II

题目大意

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

中文释义

给定一个从0开始索引的整数数组 nums,其长度为 n。你最初位于 nums[0]

数组中的每个元素 nums[i] 表示从索引 i 开始向前跳跃的最大长度。换句话说,如果你在 nums[i],你可以跳到任何 nums[i + j],其中:

0 <= j <= nums[i] 且
i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。测试用例保证你能到达 nums[n - 1]

Example

Example 1:

  • Input: nums = [2,3,1,1,4]
  • Output: 2
  • Explanation: 到达最后一个索引的最小跳跃次数是2。从索引0跳1步到索引1,然后跳3步到最后一个索引。

Example 2:

  • Input: nums = [2,3,0,1,4]
  • Output: 2

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 1000
  • 保证你能到达 nums[n - 1]

解题思路

算法描述

此代码解决了在给定的整数数组中计算到达数组末尾所需的最小跳跃次数的问题。

将这个遍历过程分为step轮,每一轮将一些可以到达的点搜罗进来,并且记录可以到达的最远的点 next_max_reach
在每轮结束的时候更新max_reach
每走一轮相当于走一步。

算法的关键步骤如下:

  1. 初始化变量:

    • start: 表示当前步骤中考虑跳跃的起始索引。
    • max_reach: 表示当前步骤能够到达的最远索引。
    • next_max_reach: 表示下一步能够到达的最远索引。
    • step: 用于记录到达数组末尾所需的步数。
  2. 遍历数组:

    • 使用一个 while 循环,条件为 max_reach 小于数组的最后一个索引(nums.size() - 1)。
    • 在每一步中,增加 step 的计数,并更新 next_max_reach
    • 通过内部的 for 循环,遍历从 startmax_reach 之间的所有索引。
    • 在每次迭代中,计算并更新可以到达的最远索引 next_max_reach
    • 循环结束后,更新 startmax_reach 为下一轮迭代的值。
  3. 返回结果:

    • max_reach 大于或等于数组的最后一个索引时,循环结束,返回 step 作为到达数组末尾所需的最小步数。

代码示例

class Solution {
public:int jump(vector<int>& nums) {int start = 0, max_reach = 0, next_max_reach = 0, step = 0;while (max_reach < nums.size() - 1) {step++;for (int i = start; i <= max_reach; i++) {next_max_reach = max(next_max_reach, i + nums[i]);}start = max_reach + 1;max_reach = next_max_reach;}return step;}
};
http://www.lryc.cn/news/272150.html

相关文章:

  • RustDesk连接客户端提示key不匹配 Key Mismatch无法连接(已解决)
  • puppeteer入门指南
  • vue3按钮点击频率控制
  • (一)Matlab数值计算基础
  • 《MySQL系列-InnoDB引擎02》InnoDB存储引擎介绍
  • 单片机大小端模式
  • Codeforces Good Bye 2023 A~E
  • 【蓝桥杯】比赛大纲整理
  • 探索 CodeWave低代码技术的魅力与应用
  • 《2023我的编程之旅》
  • C++ 二进制图片的读取和blob插入mysql_stmt_init—新年第一课
  • 向爬虫而生---Redis 基石篇2 <拓展Hash>
  • 【论文精读】A Survey on Large Language Model based Autonomous Agents
  • 23款奔驰GLC260L升级原厂540全景影像 高清环绕的视野
  • SQL 在已有表中修改列名的方法
  • QT----Visual stdio翻金币案例,附源码
  • 总结:浏览器解析html与执行JS之生命周期详解
  • aspose通过开始和结束位置关键词截取word另存为新文件
  • 深入解析美颜SDK:绿幕抠图功能的算法原理
  • 从有向带权图判断最短路径里各目标顶点顺序
  • 鼠标驱动框架:模拟键盘按键
  • ES6之Promise的链式调用
  • HTML----JavaScript操作对象BOM对象
  • 隆道数智大会回顾|第13期《如何构建绿色产业供应链新生态》(完)
  • 粒子群优化pso结合bp神经网络优化对csv文件预测matlab(3)
  • 软性演员-评论家算法 SAC
  • Nginx多域名部署多站点
  • Java的常规面试题
  • 大数据技术发展史
  • linux常见基础指令