55. Jump Game
来源:互联网 发布:神盾内网管理软件 编辑:程序博客网 时间:2024/06/06 13:02
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的地方卡住了,毕竟即使所有都是1,也能一步步走到最后,只有前面的步数不够大,跨不过0,到0就卡住了。所以我给出的解法是先线性扫描,遇到0停下来,判断这个0之前的这一段能否跨过0。
方法一:找到决定性条件进行判断
bool canJump(vector<int>& nums) { int i, j, max_step = 0; for (i = 0; i < nums.size(); i++) { if (nums[i] == 0) { for (j = i - 1; j >= 0 && nums[j] != 0; j--) { max_step = max(max_step, j + nums[j]); } if (max_step == i && i == nums.size() - 1) return true; if (max_step <= i) return false; } } return true;}
方法二: 动态规划法
其实两种方法差不多。这种是经典的动态规划问题,不停的计算局部最优解,更新全局最优解,然后判断。
- 能跳到位置i的条件:i<=maxIndex。
- 一旦跳到i,则maxIndex = max(maxIndex, i+A[i])。
- 能跳到最后一个位置n-1的条件是:maxIndex >= n-1
代码为:
bool canJump(int A[], int n) { int maxIndex = 0; for(int i=0; i<n; i++) { if(i>maxIndex || maxIndex>=(n-1)) break; maxIndex = max(maxIndex, i+A[i]); } return maxIndex>=(n-1) ? true : false;}
两种效率其实差不多,都是线性O(n).
0 0
- 55. Jump Game && 45. Jump Game II
- 55. Jump Game. 45. Jump Game II
- [LeetCode]55.Jump Game
- LeetCode 55.Jump Game
- LeetCode --- 55. Jump Game
- [Leetcode] 55. Jump Game
- [leetcode] 55.Jump Game
- 55. Jump Game
- 55. Jump Game
- [leetcode] 55.Jump Game
- *LeetCode 55. Jump Game
- LeetCode 55. Jump Game
- [leetcode] 55. Jump Game
- 55. Jump Game
- leetcode 55. Jump Game
- 55. Jump Game LeetCode
- 【LeetCode】55. Jump Game
- 55. Jump Game
- Data truncation: Data too long for column 'contents_o' at row 1 报错原因
- 191. Number of 1 Bits
- Swarm、SwarmKit、Swarm mode 对比
- JAVA导出数据到excel中大数据量的解决方法
- java之在命令环境中操作Mysql数据库
- 55. Jump Game
- C语言实现简单的socket实例
- 23种java设计模式之观察者模式
- Objective-C中的作用域详解
- jvm jdk jre区别
- 如何用img标签显示图片的某一部分
- HDU-2141-Can you find it?【二分】
- 【hdu5747】Aaronson——popcount
- ECshop 页面修改及出错处理方法基础知识(第一部分)