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

Jump Game II — leetcode

2018年10月18日 ⁄ 综合 ⁄ 共 910字 ⁄ 字号 评论关闭

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:

Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step
from index 0 to 1, then 3 steps to the last index.)

算法思路:

1.首先看看第1步能达到的最远范围。

2.再从第1步范围内所有的点出发,看第2步最远能达到的范围。

3.再从第2步范围内所有的点出发,看看第3步最远能达到的范围。

4.如此类推,直到终点。

写法一,

class Solution {
public:
    int jump(int A[], int n) {

        int step = 0;
        int far = 0, last = 0;

        for (int i=0; far < n-1; ++i) {
                far = max(far, A[i]+i);

                if (i == last) {
                        if (far == last) return INT_MAX;
                        last = far;
                        ++step;
                }
        }

        return last != far ? step+1 : step;
    }
};

写法二,

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

        for (int i=0; far < n-1; ++i) {
                if (i > last) {
                        if (far == last) return INT_MAX;
                        last = far;
                        ++step;
                }

                far = max(far, A[i]+i);
        }

        return step;
    }
};

参考

https://oj.leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii

抱歉!评论已关闭.