題目描述
Given an array of non-negative integers, you are initially positioned at the first index of the array.
給定一個非負(fù)整數(shù)的數(shù)組,初始位置在數(shù)組的第一位。
Each element in the array represents your maximum jump length at that position.
數(shù)組中的每個數(shù)字代表這個位置能跳躍的最大的長度。
Your goal is to reach the last index in the minimum number of jumps.
目標(biāo)是跳到數(shù)組的最后。
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
思路分析
需要用貪心算法的思想,在遞歸的過程中記錄當(dāng)前這一跳能跳的最遠(yuǎn)位置和下一跳能跳的最遠(yuǎn)位置(為了在跳數(shù)加了以后更新當(dāng)前能跳最遠(yuǎn)位置)
算法執(zhí)行過程
代碼實現(xiàn)
public class Solution {
/**
* 92 / 92 test cases passed.
* Status: Accepted
* Runtime: 11 ms
*
* @param nums
* @return
*/
public int jump(int[] nums) {
int jump = 0; // 當(dāng)前跳數(shù)
int last = 0; // 表示當(dāng)前這一跳的范圍,超過這個范圍就會導(dǎo)致跳數(shù)++
int cur = 0; // 表示能預(yù)判到的最遠(yuǎn)的地方,是通過當(dāng)前位置的nums[i]來預(yù)判的
for (int i = 0; i < nums.length; ++i) {
if (i > cur) {
// 有可能無論怎么跳,都不能到達(dá)終點或者越過終點,比如[3,2,1,0,4]
return -1;
}
// 需要進(jìn)行下次跳躍,則更新last和當(dāng)執(zhí)行的跳數(shù)jump
if (i > last) {
last = cur;
++jump;
}
// 記錄當(dāng)前可達(dá)的最遠(yuǎn)點
cur = Math.max(cur, i+nums[i]);
}
return jump;
}
}