跳跃游戏:给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标。
思路:局部最优:每次取最大跳跃步数(最大覆盖范围)。整体最优:最后得到最大覆盖范围,判断是否能到达终点。
跳跃游戏 II:给你一个非负整数数组 nums ,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。你的目标是使用最少的跳跃次数到达数组的最后一个位置。假设你总是可以到达数组的最后一个位置。
思路:移动下标只要遇到当前覆盖最远距离的下标,步数+1,不考虑是不是终点。
public boolean canJump(int[] nums){
int cover = 0;
if (nums.length == 1) return true;
for (int i = 0; i <= cover; i++){
cover = (i + nums[i]) > cover ? i + nums[i] : cover;
if (cover >= nums.length - 1) return true;
}
return false;
}
public int canJumpII(int[] nums){
int curDistance = 0;
int ans = 0;
int nextDistance = 0;
for (int i = 0; i < nums.length - 1; i++){
nextDistance = (nums[i] + i) > nextDistance ? nums[i] + i : nextDistance;
if (i == curDistance){
curDistance = nextDistance;
ans++;
}
}
return ans;
}