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

[LeetCode] Jump Game

时间:2014-08-12 10:15:23      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   div   

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

标签:style   blog   color   os   io   for   ar   div   

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

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