LeetCode 55. Jump Game(跳格子)
2016-05-21 07:04
465 查看
原题网址: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 =
A =
方法一:动态规划。
方法二:动态规划,优化内存。
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) { boolean[] reach = new boolean[nums.length]; reach[0] = true; int far = 0; for(int i=0; i<nums.length-1; i++) { if (!reach[i]) continue; for(int j=far+1; j<= Math.min(nums.length-1, i+nums[i]); j++) { reach[j] = true; if (j==nums.length-1) return true; } far = Math.min(nums.length-1, i+nums[i]); } return reach[nums.length-1]; } }
方法二:动态规划,优化内存。
public class Solution { public boolean canJump(int[] nums) { int far = 0; for(int i=0; i<nums.length; i++) { if (far < i) return false; far = Math.max(far, i+nums[i]); } return true; } }
相关文章推荐
- 关于人事说话真假问题
- C++抽象类
- LeetCode 54. Spiral Matrix(螺旋矩阵)
- 英雄无敌3 Mac 百度云 下载
- 陶哲轩实分析-第6章-序列的极限
- MongoDB基本用法
- LeetCode 53. Maximum Subarray(最大子数组)
- Git 分支合并
- CentOS 7拨号上网(ADSL & PPPoE)
- C++代理
- 【华为OJ】【095-四则运算】
- java设计模式之模板方法模式
- 【华为OJ】【094-多线程】
- js 遍历json
- 【华为OJ】【093-从单向链表中删除指定值的节点】
- Ps回调通知例程、Dpc定时器、内核线程使用方法.
- 【华为OJ】【092-学英语】
- 一个PsSetLoadImageNotifyRoutine回调内核注入DLL,支持xp ~ win7源码
- 文件上传小技巧/原生态【html篇】
- LeetCode 52. N-Queens II(N皇后)