[leetcode_45]Jump Game II

不停地扩展当前能到达的最远的地方。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    int jump(int A[], int n) {
        if (n <= 1) return 0;
        int min = -1;
        int max = 0;
        int maxstep = 0;
        int count = 0;
        while (true) {
            count++;
            for (int i = min + 1; i <= max; i++) {
                if (i + A[i] >= n - 1) {
                    return count;
                }
                if (i + A[i] >= maxstep)
                    maxstep = i + A[i];
            }
            min = max;
            max = maxstep;
        }
        return -1;
    }
};
Licensed under CC BY-NC-SA 4.0