55. 跳跃游戏
1.题目分析——贪心算法思路——时间复杂度-N,空间复杂度-1
- 每一步都计算从当前位置最远能够跳到哪里。
- 如果当前所到达的最远距离farthest不超过当前位置i,那么就说明前进不了了,false;
- 只有当可到达的最远距离farthest >= 最后一个元素的位置len-1时,true。
2.代码
class Solution {
public boolean canJump(int[] nums) {
if (nums == null || nums.length <= 1)
return true;
int len = nums.length;
int farthest = 0;
for (int i = 0; i < len-1; i++) {
记录在每一个下标上最远能到达的距离
farthest = Math.max(farthest,i+nums[i]);
如果最远距离 还不超过当前元素的位置,说明向前走不动了
if (farthest <= i)
return false;
}
return farthest >= len-1;
}
}
45. 跳跃游戏 II
1.题目分析——贪心选择性质
- 在每次能跳跃的可选距离范围内,即end坐标及其之前,选择一个下一步能跳跃最远的;
2.代码
class Solution {
public int jump(int[] nums) {
int len = nums.length;
1.跳跃的最大可选范围
int farthest = 0;
2.跳跃步数
int jump = 0;
3.每次跳跃的最大范围 最终坐标
int end = 0;
for (int i = 0; i < len-1; i++) {
3.5.计算出当前位置能跳出的最远坐标
farthest = Math.max(farthest,i+nums[i]);
4.跳一步,然后在该范围中i~end中选择下一次的范围
if (end == i){
jump++;
5.更新可选范围的终止坐标
end = farthest;
}
}
return jump;
}
}