jump game I // II
来源:互联网 发布:linux版启动器 编辑:程序博客网 时间:2024/05/21 06:27
/*贪心算法jump game 给出一列数组,非负,数组每个元素表示可以跳跃的最大步数第一个元素是初始化位置,编写一个函数判断是否成立(跳出数组)分析:对于数组A,共有n层,每次最多可以跳A[i]步,我们可以这样分析,加入从第0层开始,一层一层的往上跳,每次可以跳1步,那么对于跳到第i层时,距离0层的最远距离就是i-1+1+A[i-1]此时我们需要判断的就是这个最远距离是否大于njump game II对于这个问题大体和I类型相似,不过本题是这样要求的,从第0层开始跳跃,返回跳到最后的最小步数例如[2 3 1 1 4]返回 2*/#include<iostream>using namespace std;class Solution{public://jump gamebool jumpgame(int A[], int n){int reach = 1;//reach表示向右到达的最远距离for (int i = 0; i < reach&&reach < n; i++){reach = max(reach, i + 1 + A[i]);}return reach >= n;}int max(int a, int b){return a>b ? a : b;}//jump game IIint jumpgameII(int A[], int n){int countstep = 0;//计数int lastdis = 0;//表示到达的最远距离int curdis = 0;//表示使用A[i]+i到达的最远距离for (int i = 0; i < n; i++)//一层一层的跳跃{if (i>lastdis)//最远距离小于一步一步跳的节奏{countstep++;//此时才计数lastdis = curdis;}curdis = max(curdis, A[i] + i);//比较A[i]+i和reach到达的最远步数}return countstep;}};int main(){Solution s1;int a[] = { 2, 3, 1, 1, 4 };cout << s1.jumpgame(a, 5) << endl;//jump game IIcout << "输出最小步数:";cout << s1.jumpgameII(a, 5) << endl;system("pause");return 0;}
0 0
- Jump Game I , II
- jump game I // II
- Jump Game I,II
- [leetcode]Jump Game I II
- LeetCode:Jump Game I && II
- Jump Game I,II 贪心
- Jump Game I and II leetcode
- [leetcode] Jump Game I and II
- LeetCode 45/55. Jump Game i, ii
- 【LeetCode】 jump game I,II解析
- Jump Game &Jump Game II
- Jump Game/Jump Game II
- 数据结构与算法[LeetCode]——Jump Game I II
- 【leetcode】Jump Game I, II 跳跃游戏一和二
- LeetCode 55/45 Jump Game I/II-----Greedy**
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- java正则表达式
- ext在textfield 后面添加一个button
- python+opencv图像金字塔融合
- HDOJ 3746 Cyclic Nacklace
- 官方文档Coroutines的应用场景
- jump game I // II
- Socket TCP聊天通讯
- UIButton Custom
- LeetCodet题解--23. Merge k Sorted Lists(合并K个已排序的链表)
- cocos2d-Lua10网络Http&Socket编程
- 一个简单的progressbar
- 汇编,浮点运算符,fldpi,fmul等指令说明。
- 利用微信平台作为飞利浦手机产品客服渠道的可行性调查
- 解决requirejs某文件加载超时问题