【Jump Game II 】cpp
题目:
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.
For example:
Given array A = [2,3,1,1,4]
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.)
代码:
class Solution { public: int jump(vector<int>& nums) { int max_jump=0, next_max_jump=0, min_step=0; for ( int i = 0; i<=max_jump; ++i ) { if ( max_jump>=nums.size()-1 ) break; if ( max_jump < i+nums[i] ) next_max_jump = std::max(next_max_jump, i+nums[i]); if ( i==max_jump ) { max_jump = next_max_jump; min_step++; } } return min_step; } };
tips:
参考Jump Game的Greedy思路。
这道题要求求出所有可能到达路径中的最短步长,为了保持O(n)的解法继续用Greedy。
这道题的核心在于贪心维护两个变量:
max_jump:记录上一次跳跃能跳到最大的下标位置
next_max_jump:记录遍历所有max_jump之前的元素后,下一次可能跳到的最大下标位置
举例说明如下:
原始数组如右边所示:{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}
初始:max_jump=0 next_max_jump=0 min_step=1
i=0:next_max_jump=7 更新max_jump=7 更新min_step=1
i=1: 各个值不变
i=2: i+nums[i]=2+9=11>7 更新next_max_jump=11
i=3:i+nums[i]=3+6=9<11 不做更新
i=4: i+nums[i]=4+9=13>11 更新max_jump=13
...
i=7:i+nums[i]=7+7=14 >= nums.size()-1 返回min_step=2
完毕
==========================================
第二次过这道题,不太顺,大体复习了下思路。
class Solution { public: int jump(vector<int>& nums) { if ( nums.size()==0 ) return 0; int ret = 0; int nextJump = 0; int maxLength = 0; for ( int i=0; i<=maxLength; ++i ) { if ( maxLength>=nums.size()-1 ) break; nextJump = std::max(i+nums[i], nextJump); if ( i==maxLength ) { maxLength = nextJump; ret++; } } return ret; } };
==========================================
第三次过这道题,把代码改了一行,但是整体结构清晰了不少。
class Solution { public: int jump(vector<int>& nums) { if (nums.size()<2) return 0; int steps = 0; int local = 0; int next = local; for ( int i=0; i<=local; ++i ) { next = max(next, i+nums[i]); if ( i==local ) { steps++; local = next; if ( local>=nums.size()-1 ) return steps; } } return 0; } };
next只负责看下一跳能够到哪。
什么时候更新local了,再判断能否跳到尾部。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?