45 Jump Game II
https://leetcode.com/problems/jump-game-ii/#/description
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.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is2
. (Jump1
step from index 0 to 1, then3
steps to the last index.)
Note:
You can assume that you can always reach the last index.
分析及代码
先上代码
public int jump(int[] nums) {
if(nums.length < 2) {
return 0;
}
int step = 0;
int lastReach = 0;
int maxReach = 0;
for(int i = 0; i < nums.length - 1; i++) {
maxReach = Math.max(maxReach, i + nums[i]);
if(i == lastReach) {
step++;
lastReach = maxReach;
}
}
return step;
}
几个细节:
- 当
i = lastReach
时,如果不更新lastReach,那么就无法到达下一格,除非此处就结束了 - 所以因为1,我们的退出条件不是i < len, 而是
i < len - 1
,因为在len - 1处就已经确保能够抵达len - 1了
时间复杂度: O(n)