【发布时间】:2014-02-21 00:01:41
【问题描述】:
问题是获取minimum jumps 和数组中的相应索引,这些索引会导致array 的结尾以较少的跳转。例如:
{3,2,3,1,5,4} 将占用 2 jumps。
Jump 1 from index 0 to index 2
jump 2 from index 2 to index 5
跳跃,我的意思是跳跃;即需要多少跳。如果您是特定索引,则可以按该索引中的值进行跳转。
这是我在Java 中的实现,它正确地给出了最少的跳跃次数,但是我很难更新list 与indices 对应的跳跃位置。我怎样才能让它工作?
public static int minJumps2(int[] arr, List<Integer> jumps){
int minsteps=0;
boolean reachedEnd=false;
if (arr.length<2)
return 0;
int farthest=0;
for (int i=0;i<=farthest;i++){
farthest=Math.max(farthest, arr[i]+i);
if (farthest>=arr.length-1){
jumps.add(i);
reachedEnd=true;
break;
}
//jumps.add(farthest);
minsteps++;
}
if (!reachedEnd){
System.out.println("unreachable");
return -1;
}
System.out.println(minsteps);
System.out.println(jumps);
return minsteps;
}
public static void main(String[] args){
int[] arr= {3,2,3,1,5};
List<Integer> jumps=new ArrayList<Integer>();
minJumps2(arr,jumps);
}
我正在使用此处描述的跳跃游戏算法:Interview puzzle: Jump Game
【问题讨论】:
-
请清除您的问题。什么是跳跃?为什么不能一次从索引 0 跳到末尾。
-
我已经编辑了这个问题,如果有帮助的话