给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是2
。 从下标为 0 跳到下标为 1 的位置,跳1
步,然后跳3
步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
Reivew:
原本以为这个题很简单,但我做的时候才发现思维混乱,但最后却得到不错的答案
Code:
class Solution {
public int jump(int[] nums) {
if (nums.length < 2) return 0;
int res = 0, find = 0, max = 0;
for (int i = 0; i < nums.length; i++) {
max = Math.max(i + nums[i], max);
if (max >= nums.length - 1)
return res + 1;
if (find == i) {
res++;
find = max;
}
}
return res;
}
}