45. Jump Game II
Input: nums = [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.Input: nums = [2,3,0,1,4]
Output: 2Last updated
Input: nums = [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.Input: nums = [2,3,0,1,4]
Output: 2Last updated
class Solution {
public int jump(int[] nums) {
int len = nums.length;
// 方法1
// int[] steps = new int[len];
// steps[0] = 0;
// for (int i = 1; i < len; i++) steps[i] = Integer.MAX_VALUE;
// for (int i = 1; i < len; i++) {
// for (int j = 0; j < i; j++) {
// if (steps[j] != Integer.MAX_VALUE && j + nums[j] >= i) {
// steps[i] = Math.min(steps[i], steps[j] + 1);
// }
// }
// }
// return steps[len - 1];
// 方法2
int lastJumpMax = 0, steps = 0, max = 0;
for (int i = 0; i < len - 1; i++) {
max = Math.max(max, i + nums[i]);
if (i == lastJumpMax) {
steps++;
lastJumpMax = max;
}
}
return steps;
}
}