现在的位置: 首页 > 综合 > 正文

LeetCode – Jump Game

2019年04月17日 ⁄ 综合 ⁄ 共 335字 ⁄ 字号 评论关闭

一开始想DP一步步迭代更新,求出跳到最后一个的最小步数,但是时间复杂度O(nk),会超时。

再一想,发现该题只需要返回能否到达最后一个,不需要最小步数,所以迭代时候只需要保留当前能够走到的最远距离tmpMax,时间复杂度降到O(n)。

class Solution {
public:
	const int MAXVALUE = 1 << 30;
	bool canJump(int A[], int n) {

		int tmpMax = 0;

		if (n == 1)
			return true;

		for (int i = 0; i < n - 1; i++)
		{
			if (i > tmpMax)return false;

			if (tmpMax < i + A[i])
				tmpMax = i + A[i];
			if (tmpMax >= n - 1)
				return true;
		}

		return false;
	}
};

抱歉!评论已关闭.