首页 > 其他 > 详细

Jump Game

时间:2014-05-02 05:09:17      阅读:366      评论:0      收藏:0      [点我收藏+]

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.

1. 题目给定输入都是非负整数
2. 用cpos表示当前可以到达的最后一个位置,然后开始以cpos为结尾开始遍历数组,并同时更新cpos(如果i + A[i]大于当前cpos)
3. 如果在推出循环前在某个位置有cval >= n - 1,说明可以到达最后一个元素,所以之际返回true; 否则在循环结束后返回false。


class Solution {
public:
    bool canJump(int A[], int n) {
        if (n < 2) return true;
        int cpos = A[0];
        for (int i = 0; i <= cpos; ++i) {
            int cval = i + A[i];
            if (cval >= n - 1) return true;
            if (cval > cpos) cpos = cval;
        }
        
        return false;
    }
};


Jump Game,布布扣,bubuko.com

Jump Game

原文:http://blog.csdn.net/icomputational/article/details/24852073

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!