55. Jump Game && 45. Jump Game II(跳跃游戏)

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;
	}
};

可以看到两者代码没有本质区别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值