题目描述
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
解题思路
图来自 leetcode题解
如下图,开始的位置是 2,可跳的范围是橙色的。然后因为 3 可以跳的更远,所以跳到 3 的位置。
如下图,然后现在的位置就是 3 了,能跳的范围是橙色的,然后因为 4 可以跳的更远,所以下次跳到 4 的位置。
class Solution {
public int jump(int[] nums) {
/*
贪婪算法,每次在可跳范围内[start,end]选择可以使得跳的更远的位置。
*/
int len = nums.length;
if (len == 1){
return 0;
}
int step = 1; //记录最后总跳数
int start = 0; //初始只能在索引是0的地方跳
int end = nums[0];
while (end < len - 1){ //当len - 1,也就是最后一个位置 在下一次起跳范围时 就代表跳到头了
int curEnd = end;
for (int i = start; i <= end; i++) {
if (i + nums[i] > curEnd){
curEnd = i + nums[i];
start = i + 1; //下一次的起跳start
}
}
end = curEnd; //下一次的起跳end
step++;
}
return step;
}
}