zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

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

    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;
        }
    };
  • 相关阅读:
    c++ struct 使用
    c++数组、字符串操作
    c++ List、Vector、Stack、Queue使用
    十三、哈希表
    十二、234树
    十一、红黑树
    十、哈夫曼编码
    九、二叉树
    八、高级排序
    七、递归
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3906571.html
Copyright © 2011-2022 走看看