標籤:desc repr 難度 bsp dex present uri array class
題目:跳跳遊戲
難度: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.
翻譯:
給定一個非負整數數組,您最初被定位在數組的第一個索引中。
數組中的每個元素代表您在該位置的最大跳躍長度。
確定你是否能夠到達最後一個索引。
Example 1:
Input: [2,3,1,1,4]Output: trueExplanation: 第一步,跳2步到索引2,第二步跳1步到索引3,第三步跳1步到索引4,到達
第一步,跳1步到索引1,第二步跳3步到索引4,到達
Example 2:
Input: [3,2,1,0,4]Output: falseExplanation: 無論如何,你總是會到達索引3。它的最大跳轉長度為0,這使得到達最後一個索引是不可能的。
我的思路:不知道咋做。。。
答案代碼:
1 public boolean canJump(int[] A) {2 int max = 0;3 for(int i=0;i<A.length;i++){4 if(i>max) {return false;}5 max = Math.max(A[i]+i,max);6 }7 return true;8 }
答案思路:因為所跳的步數能從0到A[ i ] 都行所以只要前面能達到的最遠下標的最大值能大於後面的下標,就表示能跳到,否則跳不到。能達到的最遠下標為A[i] + i 。
eg.:[3,2,1,0,4]
前面三個的能達到的最遠下標最大值為3,所以此時最遠只到下標3,而下標3的最遠下標是自己,到了下標4進行判斷髮現前面的最遠下標比自己的下標小,所以跳不到。
LeetCode第[55]題(Java):Jump Game