【LeetCode】Jump Game & Jump Game II
来源:互联网 发布:最游记一键淘宝端 编辑:程序博客网 时间:2024/04/30 12:53
参考链接
http://blog.csdn.net/pickless/article/details/9855891http://www.cnblogs.com/tgkx1054/archive/2013/05/23/3095115.html
http://www.cnblogs.com/xinsheng/p/3510504.html
题目描述
Jump Game
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
Jump Game II
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: bool canJump(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int max = 0; for (int i = 0; i < n && i <= max; i++) { max = A[i] + i > max ? A[i] + i : max; } return max >= n - 1; }};Jump Game II
class Solution { public: int jump(int A[], int n) { int *step=new int[n]; memset(step,0,sizeof(step)); int lasti=0,maxreach=A[0],reachindex; for(int i=1;i<n;i++) { if(lasti+A[lasti]>=i) { step[i]=step[lasti]+1; } else { step[i]=step[reachindex]+1; lasti=reachindex; } if(i+A[i]>maxreach) { maxreach=i+A[i]; reachindex=i; } } return step[n-1]; } };
class Solution {public: int jump(int A[], int n) { if(n <= 1) return 0; int start = 0, end = 0; int cnt = 0; while(end < n-1) { int maxdis = 0; for(int i = start; i <= end; i ++) { maxdis = max(maxdis, A[i]+i); } start = end+1; end = maxdis; cnt ++; } return cnt; }};
推荐学习C++的资料
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- [LeetCode] Jump Game II
- Lua学习与交流——Lua string库经验分享
- Struts2 拦截器
- LeetCode Median of Two Sorted Arrays
- HDOJ 2243 考研路茫茫——单词情结
- 华为编程大赛-查找最大的不重复数
- 【LeetCode】Jump Game & Jump Game II
- Java中SimpleDateFormat,String.format的用法
- Server.MapPath()相关
- c2java 第6篇 图的表示,最短路,圈检测和拓扑排序
- PHP从零单排(五)PHP对数组的处理
- 杭电 1157 Who's in the Middle
- java string 判断中文汉字及中文字符
- 基于ARM Contex-A8 Tiny210的简单室内人员数目监测系统实现(2)
- 【转】H2数据库攻略