您的位置:首页 > 其它

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 =
[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: