您的位置:首页 > 编程语言 > Java开发

leetCode练习(55)

2016-10-10 14:20 232 查看
题目:Jump Game

难度:medium

问题描述:

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
.

解题思路:

方法一:

使用了动态规划方法,依次计算第n、n-1、n-2块石头能否达到。第I块石头能否到达取决于第(I+1)到第(I+nums[i])块石头间是否有一块能到达,如果有,那第I块石头也就能到达。这个方法可以算出每一块石头的Boolean值,但是提交时超时啦~ 但我认为仍是一个非常高效的方法,具体代码如下:

boolean[] cap;
public boolean canJump(int[] nums) {
cap=new boolean[nums.length];
for(int i=nums.length-1;i>=0;i--){
cap[i]=canget(nums,i);
}
return cap[0];
}
public boolean canget(int[]nums,int steps){
if(steps+nums[steps]>=nums.length-1){
return true;
}
for(int i=nums[steps];i>0;i--){
if(cap[steps+i]==true){
return true;
}
}
return false;
}

方法二:

使用了greedy 贪心算法,在第I块石头上,则下一次需要跳的步数next取决于MAX((1+nums[I+1]),,,,,,,,,,(nums[i]+nums[I+1])),保证每次可能走得最远。但这样是否能保证Boolean的正确性我表示怀疑。但也只有这样我才能提交通过哈~具体代码如下:

public static boolean canJump2(int[] nums) {
int len=nums.length;
int index=0; //当前位置
int temp=0;
int next=0;
int laststep=len-1;
if(len==1){
return true;
}
while(index<len-1){
temp=0;
next=0;
if(index+nums[index]>=len-1){
return true;
}
if(laststep==0){
break;
}
for(int i=1;i<=nums[index];i++){
if(i+nums[index+i]>temp){
next=i;
temp=i+nums[index+i];
}
}
index+=next;
laststep--;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息