leetcode45 跳跃游戏2——贪心 (C++/Python)
题目描述:
给定一个长度为 n
的 0 索引整数数组 nums
。初始位置为 nums[0]
。
每个元素 nums[i]
表示从索引 i
向前跳转的最大长度。换句话说,如果你在 nums[i]
处,你可以跳转到任意 nums[i + j]
处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1]
的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]
。
示例 1:
2
1
3
示例 2:
输入: nums = [2,3,0,1,4] 输出: 2
提示:
1 <= nums.length <= 10^4
0 <= nums[i] <= 1000
- 题目保证可以到达
nums[n-1]
解法解析:
int maxIndex 为所能到达最大下标 maxIndex=max(maxIndex , i + nums[i]),值得注意只有当maxindex>i 时才能更新值(但题目前提时能到达终点,所以无需顾虑)
当 maxIndex 在nums【i】处更新值,代表先跳到nums【i】再往后跳能到的地方更远,所以step+1(跳到nums[i]处)
C++
class Solution { public: int jump(vector<int>& nums) { //fronm this index the farest we can get to -> maxIndex int length = nums.size(); int destination=0; int maxindex=0; int step=0; for(int i=0;i<length-1;i++) { if (maxindex>=i) { maxindex=max(maxindex,nums[i]+i); if(i==destination) {//maxindex 在此处有更新 destination=maxindex; step++; } } } return step; } };
python
1 2 3 4 5 6 7 8 9 10 11 | class Solution: def jump( self , nums: List [ int ]) - > int : n = len (nums) maxIndex,destination,step = 0 , 0 , 0 for i in range (n - 1 ) : if maxIndex > = i: maxIndex = max (maxIndex,i + nums[i]) if i = = destination: destination = maxIndex step + = 1 return step |
说起来我老是忘记python没有 ++ 和 --
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具