[leetcode]Jump Game
2016-01-18 17:48
253 查看
题目描述如下:
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.
类似跳格子,判断能否到达最后一个。
明显的动归题,受到昨天Coin Change的影响Coin Change,第一版代码如下:
在最后一个大数据的测试下TLE了。
之后对此做了各种优化,判断在一个点的时候最远能到达的位置有没有超过最后一个元素。个人感觉思路是没有错的,然而各种TLE和RE。
无奈最后参考了别人的代码。
很巧妙的是记录当前能到达的最远距离与点的位置的比较。我之前所标记的是点的位置因此逻辑变得很复杂。
总归是自己对动归运用的不熟练,还要多练习。
题目链接:https://leetcode.com/problems/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.
类似跳格子,判断能否到达最后一个。
明显的动归题,受到昨天Coin Change的影响Coin Change,第一版代码如下:
public class Solution { public boolean canJump(int[] nums) { boolean judgeArray[] = new boolean[nums.length]; judgeArray[0] = true; int i, j; for(i = 0; i < nums.length; i++){ if(judgeArray[i]){ int limit = i + nums[i] < nums.length - 1 ? i + nums[i] : nums.length - 1; for(j = i + 1; j <= limit; j ++) judgeArray[j] = true; } } return judgeArray[nums.length - 1]; } }
在最后一个大数据的测试下TLE了。
之后对此做了各种优化,判断在一个点的时候最远能到达的位置有没有超过最后一个元素。个人感觉思路是没有错的,然而各种TLE和RE。
无奈最后参考了别人的代码。
public class Solution { public boolean canJump(int[] nums) { int max =0; for(int i=0;i<nums.length; i++){ if(max<i) return false; max=Math.max(max, i+nums[i]); } return true; } }
很巧妙的是记录当前能到达的最远距离与点的位置的比较。我之前所标记的是点的位置因此逻辑变得很复杂。
总归是自己对动归运用的不熟练,还要多练习。
题目链接:https://leetcode.com/problems/jump-game/
相关文章推荐
- DIalog实现蒙版指引提示效果
- 通过Oracle补充日志,找到锁阻塞源头的SQL
- php实现分页,上一页下一页
- PHP PSR-3 日志接口规范 (中文版)
- Spring 2.0技术手册 -3
- hdu 2276 Kiki & Little Kiki 2(矩阵递推)
- iOS学习心得——UITableViewCell的复用
- Python-strip()方法
- C#技术分享【PDF转换成图片——13种方案】(2013-07-25重新整理)
- DB2错误代码
- PHP超全局变量
- 上传图片预览插件(转)
- html中怎么去掉input获取焦点时候的边框
- 关于安卓Fragment onCreateView()重复执行
- Xcode7 使用自带git身份不确认的问题
- sed在行首或者行尾添加内容
- sed在行首或者行尾添加内容
- PHP PSR-2 代码风格规范 (中文版)
- python 对象与变量
- Zabbix 编译安装 (zabbix-2.4.3 server_install )