个人记录-LeetCode 55. Jump Game
来源:互联网 发布:java获取本机端口号 编辑:程序博客网 时间:2024/05/29 18:44
问题:
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.
代码示例:
主要思路是:
每跳一次,都计算出下一次跳跃,可达到的最大位置。
然后,判断下一次可达到的最大位置,是否可达到终点,是否大于等于下一次的起跳位置。
public class Solution { public boolean canJump(int[] nums) { //第一次跳跃,最远的位置,即0+num[0] int nextEnd = nums[0]; //最远位置,大于等于最后一个位置,可直接结束 if (nextEnd >= nums.length - 1) { return true; } //初始位置为0,为了有实际的前进,下一次跳跃的起始位置为1 int nextBegin = 1; //保存下一次跳跃的最远位置 int curMax = -1; while(nextEnd < nums.length - 1) { for (int i = nextBegin; i <= nextEnd; ++i) { //计算出从当前位置,可跳跃达到的最远位置 if (i + nums[i] > curMax) { curMax = i + nums[i]; //最远位置,大于等于最后一个位置,可直接结束 if (curMax >= nums.length - 1) { return true; } } } //下一次预期的起跳位置,为本次最后一个位置的下一个 nextBegin = nextEnd + 1; //下一次可达到的最远位置 nextEnd = curMax; curMax = -1; //下一次最远的位置,小于预期的起跳位置,即跳不动了,结束 if (nextEnd < nextBegin) { break; } } return false; }}
0 0
- 个人记录-LeetCode 55. Jump Game
- 个人记录-LeetCode 45. Jump Game II
- [LeetCode]55.Jump Game
- LeetCode 55.Jump Game
- LeetCode --- 55. Jump Game
- [Leetcode] 55. Jump Game
- [leetcode] 55.Jump Game
- [leetcode] 55.Jump Game
- *LeetCode 55. Jump Game
- LeetCode 55. Jump Game
- [leetcode] 55. Jump Game
- leetcode 55. Jump Game
- 55. Jump Game LeetCode
- 【LeetCode】55. Jump Game
- leetcode 55. Jump Game
- [LeetCode] 55. Jump Game
- LeetCode 55. Jump Game
- LeetCode *** 55. Jump Game
- 机器学习笔记
- 利用RecyclerView实现的一个动画给变item的位置和左右滑动删除该RcyclervView的Item条目
- Power OJ 2543 赛场布置(网络流最小割)
- Notice: Undefined index: act
- 搭建NFS服务器
- 个人记录-LeetCode 55. Jump Game
- [伪位运算生成树] HDU 5629 Clarke and tree
- Android Webview 获取网页form 提交的数据
- Lua初学者笔记
- const修饰符的作用
- jq上传进度条
- NestedScrolling机制(三)——机制本质以及源码解析
- 灵活的指向const 的引用
- java向上转型和向下转型