Jump Game
看到题目OK 似乎可以用BFS来做,这也是博主采用的方法,智商不够想不到smart的方法,开开心心的去提交果然超时,可恶。在讨论区逛了一番之后发现一个比较好的解法,主要也适用于第二题的通用解法,直接上代码。
class Solution {
public:
bool canJump(vector<int>& nums) {
int m = nums.size();
int max_end = 0, end = 0;
int i = 0;
while (end < m - 1)
{
for (; i <= end; i++)
max_end = max(max_end, i + nums[i]);
if (max_end >= m - 1)
return true;
if (max_end == end)
break;
end = max_end;
}
return m == 1 ? true : false;
}
};
可能小伙伴刚看到这个代码感觉有点奇怪,其实仔细来看一下这个代码,while循环中的for循环,这个for循环确定了当前我所能走到的最远距离,同时要注意这个i,则是上一个阶段所能走到最远距离下一个。可能解释的不是很清楚,但是我相信看到代码再仔细推敲一下一切就明白了。
对于BFS的做法我也把它切贴出来,BFS非常容易理解。
class Solution {
public:
bool canJump(vector<int>& nums) {
queue<int> q;
int m = nums.size();
if (m == 0)
return true;
q.push(0);
while (!q.empty())
{
int temp = q.front();
if (temp == m - 1)
return true;
q.pop();
for (int i = 1; i <= nums[temp]; i++)
q.push(temp + i);
}
return false;
}
};
但是超时。
45. Jump Game II
可以看到这题和上面其实有一些隐含条件,就是所给数据一定能走到最后,不会出现上面false的情况。这也是可以利用的条件,但是在这里就不利用了,直接上代码。
class Solution {
public:
int jump(vector<int>& nums) {
int m = nums.size();
int end = 0, max_end = 0, i = 0;
int res = 0;
while (end < m - 1)
{
res++;
for (; i <= end; i++)
{
max_end = max(max_end, i + nums[i]);
}
if (max_end >= m - 1)
return res;
if (end == max_end)
break;
end = max_end;
}
return m == 1 ? 1 : -1;
}
};
可以看到两者代码没有本质区别。