45. 跳跃游戏 II
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
链接: https://leetcode-cn.com/problems/jump-game-ii/.
在做本题之前,希望大家可以首先做一下leetcode 55. 跳跃游戏
链接:https://leetcode-cn.com/problems/jump-game/.
本题所用到的是贪心思想—即由局部最优解而得出全局最优解。
本题主要目的是找出在可跳的范围内最大值。
// 自己思想代码
public int jump(int[] nums) {
if(nums.length == 1) return 0;
//time等于1是因为算上刚开始0位置时调的一次
int max = nums[0], time = 1, start = 1;
while(max < nums.length - 1){
int temp = max;
//找到在1和局部最大值之间的最大值
for(int j = start; j <= temp; j++){
max = max > nums[j] + j ? max : nums[j] + j;
}
//下一次是从最大值开始计算
start = temp + 1;
time ++;
}
return time;
}
以下是leetcode官方题解
// LeetCode官方题解
public int jump(int[] nums) {
int maxPosition = 0, end = 0, step = 0;
for(int i = 0; i < nums.length - 1; i++){
//即每次跳到最大值就继续寻找下一个最大值
maxPosition = Math.max(maxPosition, nums[i] + i);
if(i == end){
step ++;
end = maxPosition;
}
}
return step;
}