LeetCode 55 Jump Game
2016-05-19 23:11
357 查看
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 =
A =
方法一:贪心法,因为若要到达终点,每个台阶都是必经之路,因此在每个台阶都算一下可达的最远方。最终超过终点距离就对了。
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 boolean canJump(int[] nums) { int reach = 1;//最右能跳到哪里 for (int i = 0; i < reach && reach < nums.length; i++) reach = Math.max(reach, i + 1 + nums[i]); return reach >= nums.length; }方法二:动态规划
public boolean canJump2(int[] nums) { int[] surplus = new int[nums.length];//在每个台阶,剩余的最大步数 for (int i = 0; i < nums.length; i++) { surplus[i] = Math.max(surplus[i - 1], nums[i - 1]) - 1; if (surplus[i] < 0) return false; } return surplus[nums.length - 1] >= 0; }
相关文章推荐
- Java注册帐号邮箱激活验证实现
- vsftpd用户配置 No.2
- POJ 3164 Command Network(最小树形图)
- Ubuntu14.04安装后配置
- 第十三周周记
- Spring学习(三)IOC控制反转与DI依赖注入
- ffmpeg tutorial2学习--使用SDL显示到屏幕上
- Android消息机制字典型探究(一)
- 条件随机场CRF HMM,MEMM的比较
- Codeforces Beta Round #37 C. Old Berland Language 暴力 dfs
- IM聊天系统
- C# Sort排序
- dubbo服务者配置说明
- dubbo服务者配置说明
- Oracle10GODP连接11G数据库,出现ORA - 1017用户名/口令无效; 登录被拒绝 的问题
- MDWIKI
- 自搭博客日记2
- 优化的网站注册时[验证邮箱]的流程
- 字符串反转方法汇总
- Google官方 由浅入深详解Fragment【附Fragment使用常见问题】