55. 跳跃游戏 - 力扣(LeetCode)
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int reach = 0;
for(int i = 0; i < n; i++){
if(i > reach)
{
return false;
}
reach = max(i+nums[i], reach);
}
return true;
}
};
45. 跳跃游戏 II - 力扣(LeetCode)
改进上一题的代码,但是没有通过全部测试用例:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if(n <= 1)
{
return 0;
}
int reach = 0;
int cnt = 0;
for(int i = 0; i < n; i++){
int last_reach = reach;
if(i > reach)
{
return false;
}
reach = max(i+nums[i], reach);
if(last_reach != reach)
cnt++;
}
return cnt-1;
}
};
正确的代码
每次跳找这次跳跃的范围内能跳到的最远值;
举例子nums[a] = 3,那就找a~a+3里面能跳的最远的那个;接下来每次都找最远的,最终结果就是最远的;
class Solution {
public:
int jump(vector<int>& nums) {
int start = 0;
int end = 1;
int cnt = 0;
while(end < nums.size())
{
int maxreach = 0;//每次跳的最大值
for(int i = start; i < end; i++)
{
maxreach = max(i+nums[i], maxreach)//找最远的
}
//下一次跳的初值
start = end;
end = maxreach+1;
cnt++;
}
return cnt;
}
};