本题来自:力扣-面试经典 150 题
面试经典 150 题 - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台https://leetcode.cn/studyplan/top-interview-150/
题解:
class Solution {
public int jump(int[] nums) {
int end = 0;
int steps = 0;
int maxPosition = 0;
for(int i = 0;i < nums.length-1;i++){
maxPosition = Math.max(maxPosition, nums[i] + i);
if(i == end){
end = maxPosition;
steps++;
}
}
return steps;
}
}
思路如下:
从数组的第 0 个位置开始跳,跳的距离小于等于数组上对应的数。求出跳到最后个位置需要的最短步数。比如上图中的第 0 个位置是 2,那么可以跳 1 个距离,或者 2 个距离,我们选择跳 1 个距离,就跳到了第 1 个位置,也就是 3 上。然后我们可以跳 1,2,3 个距离,我们选择跳 3 个距离,就直接到最后了。所以总共需要 2 步。
这里要注意一个细节,就是 for 循环中,i < nums.length - 1,少了末尾。因为开始的时候边界是第 0 个位置,steps 已经加 1 了。如下图,如果最后一步刚好跳到了末尾,此时 steps 其实不用加 1 了。如果是 i < nums.length,i 遍历到最后的时候,会进入 if 语句中,steps 会多加 1。