您的位置:首页 > 编程语言 > C语言/C++

LeetCode 47. Jump Game II

2014-06-30 03:12 288 查看
思路是每次迭代都考察在第step步最多能走到多远(next);在下次迭代则考察第step+1步能走多远。当next >= n-1时停止迭代。

如,输入[2, 3, 1, 1, 4], 则:

第一步访问下标0, 发现最远能到下标2;

第二步访问下标1, 2, 发现最远下标next = 4, next >= n-1, 停止迭代。

有点像BFS.

代码:

class Solution
{
public:
int jump(int A[], int n)
{
int step = 0;

for (int i=0, bound=0, next=0; next < n - 1; ++ step)
{
for ( ; i <= bound; ++ i)
{
next = max(next, i+A[i]);
}
bound = next;
}

return step;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode C++