問題是得到minimum jumps
和數組中相應的索引,導致跳轉較少的array
結束。例如: {3,2,3,1,5,4}
需要2 jump
s。達到陣列末端所需的最小跳躍數 - 獲取索引位置
Jump 1 from index 0 to index 2
jump 2 from index 2 to index 5
By跳,我的意思是跳;即需要多少次啤酒花。如果你是一個特定的索引,你可以跳過該索引中的值。
這是我在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跳到最後跳轉。 –
我編輯了這個問題,如果有幫助 –