算法分析与设计week04--45.Jump Game II
来源:互联网 发布:职场女强人知乎 编辑:程序博客网 时间:2024/06/07 22:15
45.Jump Game II
Description
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.
Note:
You can assume that you can always reach the last index.
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.)
Analyse
思路和Jump Game类似,只是原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step步)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。
class Solution {public: int jump(vector<int>& nums) { int step = 0; // 当前步数 int lastReach = 0; // step-1时可达最远距离 int reach = 0; // step时可达最远距离 for (int i = 0; i < nums.size() && i <= reach; i++) { if (i > lastReach) { step++; lastReach = reach; } reach = max(reach, i + nums[i]); } if (reach >= nums.size() - 1) return step; }};
复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)
阅读全文
0 0
- 算法分析与设计week04--45.Jump Game II
- 算法分析与设计week04--55.Jump Game
- 算法分析与设计第九周:45. Jump Game II
- 算法分析与设计课程(9):【leetcode】Jump Game
- LeetCode 45. Jump Game II|贪心算法
- [LeetCode]45. Jump Game II &&贪心算法
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- c语言解决杨辉三角问题
- 高可用Docker容器云在58集团的实践
- ubuntu 16.04 安装 eclipse教程和总结
- 虚拟货币“跳水“,产业实践才是检验区块链的唯一标准
- spring-mvc 中的单例模式的实例
- 算法分析与设计week04--45.Jump Game II
- 可重用代码的基本特性
- MongoDB:11-MongoDB 关系
- Python中list、tupe、dic、set的使用小记
- 工作台的进化
- 微信Android视频编码爬过的那些坑
- Wi-Fi 爆重大安全漏洞,Android、iOS、Windows 等所有无线设备都不安全了
- iOS推送配置手把手指南
- 礼物 期望dp