[leetcode]Jump Game I II
来源:互联网 发布:天刀捏脸详细数据 编辑:程序博客网 时间:2024/05/01 01:50
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
.
解题思路:依次计算每个元素所能跳跃的最大步数,判断所跳跃的步数是否可以达到数组最后的元素,
如果最大跳跃距离等于当前元素所在位置,则表明本元素值为0,且跳跃会在此元素终止前进。
bool canJump(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(n <= 1) return true; int i = 0; int e = 0; while(true){ e = max(e, A[i] + i); if(e >= n - 1) return true; //跳跃被阻塞 if(e == i) break; i++; } if(e >= n - 1) return true; 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.)
int jump(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. // 贪心算法的应用 int i = 0, tmp = 0, maxx = 0, sum = 0; while(i < n){ if(tmp >= n - 1) break; //如果到达数组尾break while(i <= tmp){//当前元素所能到达的最远处 maxx = max(maxx, i + A[i]);//记录在当前范围内某元素所能达到的最远处 i++; } tmp = maxx;//步数加1 sum++; } return sum; }
- [leetcode]Jump Game I II
- LeetCode: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 I , II
- jump game I // II
- Jump Game I,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
- 今天在知乎看见:程序员如何在30岁达到百万年薪?
- IOS-本地存储-NSUserDefaults
- Unite2014大会的一些笔记
- HTTP协议知识
- NYOJ244十六进制的简单运算
- [leetcode]Jump Game I II
- Lesson_for_java_day12--String类的五个练习题
- poj2425
- 转载:c++开源机器学习库(更新中20140330)
- 操作系统作业
- ARM Timer Watchdog
- Java中时间的计算 年月日小时分钟秒毫秒微秒
- ipa有些手机能装有些手机不能装
- java内省机制