45. 跳跃游戏 II
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
思路一:从左往右贪心法
// 时间复杂度 O(N),空间复杂度 O(1)
// 贪心法
class Solution {
public int jump(int[] nums) {
// i 和 end 标记了可以选择的跳跃步数
// farthest 标记了所有选择 [i..end] 中能够跳到的最远距离
// jumps 记录了跳跃次数
int farthest = 0;
int end = 0;
int jumps = 0;
// 题目说必然可以到达最后一个位置,所以i<n-1
for(int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if(i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
}
思路二
时间复杂度:O(n^2)
空间复杂度:O(1)
public int jump(int[] nums) {
int position = nums.length - 1; //要找的位置
int steps = 0;
while (position != 0) { //是否到了第 0 个位置
for (int i = 0; i < position; i++) {
if (nums[i] >= position - i) {
position = i; //更新要找的位置
steps++;
break;
}
}
}
return steps;
}