1、题目描述
给你一个非负整数数组 nums ,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
2、算法分析
思路:
在区间范围内,找到能跳最远的距离。
定义三个变量:
maxJump:记录当前能跳的最远位置
step:记录跳跃的次数
end:记录本次跳跃的边界
注意:
最后一个位置的时候是不用跳的,因为最后一个位置。
求当前位置和当前位置加上nums[i]的值:maxJump = Math.max(maxJump,nums[i] + i);
如果当前位置等于end的话,说明到达当前区间的尾区间。步数++;更新边界。
3、代码实现
class Solution {
public int jump(int[] nums) {
// 当前能跳的最远位置
int maxJump = 0;
// 记录跳跃的次数
int step = 0;
// 记录本次跳跃的边界,到达边界跳跃次数 + 1
int end = 0;
// 最后一个位置不用跳了
for(int i = 0;i < nums.length - 1;i++){
// nums[i] + i:当前下标 + nums[i]:跳几步
maxJump = Math.max(maxJump,nums[i] + i);
// 等于当前区间的尾区间的时候,步数++;更新边界
if(i == end){.
step++;
end = maxJump;
}
}
return step;
}
}
这种方式更好理解
class Solution {
public int jump(int[] nums) {
int step = 0;
// 定义区间
int start = 0;
int end = 0;
// 区间结尾到数组到第二个元素
while(end < nums.length - 1){
int max = 0;
// 遍历区间,找到跳跃范围最大的
for(int i = start;i <= end;i++){
max = Math.max(max,i + nums[i]);
}
// 改变下标位置
start = end + 1;
end = max;
step++;
}
return step;
}
}