題目描述
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.
數組中的每個數字代表這個位置能跳躍的最大的長度。
Your goal is to reach the last index in the minimum number of jumps.
目標是跳到數組的最后。
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.
思路分析
需要用貪心算法的思想,在遞歸的過程中記錄當前這一跳能跳的最遠位置和下一跳能跳的最遠位置(為了在跳數加了以后更新當前能跳最遠位置)
算法執行過程
代碼實現
public class Solution {
/**
* 92 / 92 test cases passed.
* Status: Accepted
* Runtime: 11 ms
*
* @param nums
* @return
*/
public int jump(int[] nums) {
int jump = 0; // 當前跳數
int last = 0; // 表示當前這一跳的范圍,超過這個范圍就會導致跳數++
int cur = 0; // 表示能預判到的最遠的地方,是通過當前位置的nums[i]來預判的
for (int i = 0; i < nums.length; ++i) {
if (i > cur) {
// 有可能無論怎么跳,都不能到達終點或者越過終點,比如[3,2,1,0,4]
return -1;
}
// 需要進行下次跳躍,則更新last和當執行的跳數jump
if (i > last) {
last = cur;
++jump;
}
// 記錄當前可達的最遠點
cur = Math.max(cur, i+nums[i]);
}
return jump;
}
}