首页 > 其他 > 详细

[LeetCode] Jump Game

时间:2014-08-12 10:15:23      阅读:282      评论: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.

这个题要小心各种陷阱,一不小心就会死循环什么的。

class Solution {
public:
    bool canJump(int A[], int n) {
        if(n<=1)
          return true;//输入[0]输出true
        int Index = A[0];
        while(Index<n-1){
           if(A[Index]!=0)
             Index += A[Index];
           else{
               int Index0 = Index;
               for(int i = Index0-1;i>=0;i--){//遇到不前进的,往前回退一步,因为能到i,经过前面的步骤也能到i-1;
                   Index = i + A[i];
                   if(Index>Index0)
                       break;
                   else
                       continue;
               
               }//end for
               
               if(Index<=Index0)//经过处理后依然跨不过坎
                   return false;
           }//end if      
        }//end while
        if(Index>=n-1)
            return true;
        else
            return false;
    }
};

 

[LeetCode] Jump Game,布布扣,bubuko.com

[LeetCode] Jump Game

原文:http://www.cnblogs.com/Xylophone/p/3906571.html

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