您的位置:首页 > 其它

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