首页 > 代码库 > Leetcode:Jump Game 跳跃楼梯

Leetcode:Jump Game 跳跃楼梯

Jump Game:

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.

Determine if you are able to reach the last index.

For example:

A = [2,3,1,1,4], return true.A = [3,2,1,0,4], return false.

 

解题分析:

每一层最大可以跳 A[i] 步,当然可以 跳 0,1,2...A[i]中的任意步

我们可以 从下表0出发,每一层的时候我们都依次跳 1,2,3...A[i]步,并且每跳一步,我们就更新 可以达到的最到楼层

如果最后能超过 最高层,说明能够达到

class Solution {public:    bool canJump(int A[], int n) {        assert(A != NULL && n >= 0);        int reachIndex = 0;        for (int i = 0; i <= reachIndex && reachIndex < n; ++i) {            reachIndex = max(reachIndex, i + A[i]);        }        return reachIndex >= n - 1;    }};

 

Jump Game II:

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.)

 

解题分析:

此题需要求解 最小步数

我们每次尝试 从每一层跳最远

例如,假设 [left, right] 是当前跳跃能覆盖的区间

我们从left到right遍历,我们查找 从[left, right]区间任一楼层 能够 跳到的 最高楼层,如果 可以达到的最高楼层 >= 实际的最高楼层,立即返回

否则,我们 更新为 left = oldRight + 1, 即 下一步 从 原来的right+1 开始跳,因为 原来的right代表了 这一步可以到达的最高楼层

class Solution {public:    int jump(int A[], int n) {        assert(A != NULL && n >= 0);        if (n == 1) return 0;        int step = 0;        int left = 0;        int right = 0;                while (left <= right) {            ++step;            const int rightTmp = right;            for (int i = left; i <= rightTmp; ++i) {                int newRight = i + A[i];                if (newRight >= n - 1) return step;                if (newRight > right) right = newRight;            }            left = rightTmp + 1;        }        return 0;    }};