LeetCode- Jump game
来源:互联网 发布:淘宝的卡券包在哪里 编辑:程序博客网 时间:2024/06/05 14:42
- jump game I
- 题目描述
- 思路阐述
- 贪心
- 动态规划
- 代码
- 下一篇
- jump game I
jump game I
1 . 题目描述
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.
中文阐述:给出一个非负整数数组,你最初定位在数组的第一个位置。
数组中的每个元素代表你在那个位置可以跳跃的最大长度。
判断你是否能到达数组的最后一个位置。
A[0]可以跳到A[1]A[2],跳到A[2],最多跳1步,到A[3],最多跳一步,到A[4],最多跳一步,到A[5].true
A[0]到A[3],A[3]去不了。第二个例子false。
思路阐述
1. 贪心
依次遍历数组,求每一步所能达到的最远位置的最大值
1. 这个最大值如果大于或等于n - 1,则表示一定能达到最后一个位置。
2. 而如果在遍历过程中,发现某个位置(数组下标)大于最远位置了,那也就是说不可能到达这个位置,当然就不可能到达最后了;
比如样例中第二个例子:
1. 扫描到3,far = 0 + 3
2. 扫描到2,far = max(3, 1 + 2) = 3
3. 扫描到1,far = max(3, 2 + 1) = 3
4. 扫描到0,far = max(3, 3 + 0) = 3
5. 扫描到4,此时,数组下标为4,4 > 3,失败
2. 动态规划
设状态为 f[i],表示从第 0 层出发,走到 A[i] 时剩余的最大步数,则状态转移方程为:f[i] = max(f[i − 1], A[i − 1]) − 1, i > 0代码 1// LeetCode, Jump Game// 思路 1,时间复杂度 O(n),空间复杂度 O(1)
依次遍历数组,设maxJump为当前最远能跳到的距离。
1. 如果i+maxJump>=n-1说明true
2. 若maxJump=0说明没办法跳了,为false.
3. 每走一步,即i++时,maxJump-=1。
代码
代码一(对应贪心算法)
class Solution{ public: bool canJump(int A[], int n) { int max = 0; for(int i = 0; i < n; i++) { if(i > max) return false; int nowMax = i + A[i]; if(nowMax > max) max = nowMax; } return true; }};
代码二(动态规划)
class Solution {public: bool canJump(int A[], int n) { if (n == 1) return true; int maxJump =0;//current you can jump for (int i = 0; i < n; i++){ maxJump--; if (maxJump < A[i]) maxJump = A[i]; if (!maxJump) return false; if (maxJump + i >= n - 1 ) return true; } return false; }};
4. 下一篇
下一篇是jump game II 参见我的博客列表。
- LeetCode Jump Game && Jump GameII
- [LeetCode]Jump Game II、Jump Game
- 【LeetCode】Jump Game & Jump Game II
- leetcode Jump Game & Jump Game II
- leetcode之Jump Game && Jump Game II
- [leetcode]Jump Game &&Jump Game II
- 【LeetCode】Jump Game && Jump Game II
- [Leetcode]Jump Game && Jump Game II
- Leetcode之Jump Game & Jump Game II
- Jump Game 和Jump Game II---LeetCode
- LeetCode-Jump Game & Jump Game II
- 【Leetcode】【python】Jump Game/Jump Game II
- LeetCode: Jump Game
- LeetCode: Jump Game II
- LeetCode Jump Game
- LeetCode Jump Game II
- LeetCode : Jump Game
- LeetCode: Jump Game II
- BAT通吃人工智能?垂直行业仍有机遇
- poj2251——Dungeon Master
- 关于预处理
- linux调试器的实现---断点的实现
- 搞定BAT Java面试题
- LeetCode- Jump game
- SPI
- React高级指南(三)【Refs and the DOM】
- Java-script学习笔记--函数
- Java实现时钟
- 未来七年手机市场预测分析:华为能否登顶?
- jsp/servlet第四章第四节session范围实例
- 华为轮值CEO郭平:ICT技术是推动亚太经济关键使能器
- linux下为集群配置ssh无密码登录