码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:Jump Game 跳跃楼梯

时间:2014-06-22 23:11:57      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

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;
    }
};

 

 

Leetcode:Jump Game 跳跃楼梯,布布扣,bubuko.com

Leetcode:Jump Game 跳跃楼梯

标签:style   class   blog   code   http   tar   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3800168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!