大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。
一開始想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;
}
};
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/118467.html原文链接:https://javaforall.cn